為了提高用戶體驗,達到理想的效果,一般不直接使用系統提供的對話框,而使用自定義的對話框。 ...
為了提高用戶體驗,達到理想的效果,一般不直接使用系統提供的對話框,而使用自定義的對話框。
步驟:
1、創建對話框的佈局文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical"> 6 7 <!--標題部分--> 8 <TextView 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:text="提示信息" 12 android:gravity="center" 13 android:layout_margin="30dp" 14 android:textSize="20sp"/> 15 16 <!--提示消息部分--> 17 <TextView 18 android:layout_width="match_parent" 19 android:layout_height="wrap_content" 20 android:id="@+id/tipInfo" 21 android:text="消息內容" 22 android:gravity="center"/> 23 24 <!--按鈕部分--> 25 <LinearLayout 26 android:layout_width="match_parent" 27 android:layout_height="wrap_content" 28 android:orientation="horizontal" 29 android:layout_margin="30dp"> 30 <Button 31 android:layout_width="wrap_content" 32 android:layout_height="wrap_content" 33 android:id="@+id/okBtn" 34 android:text="確定"/> 35 <Button 36 android:layout_width="wrap_content" 37 android:layout_height="wrap_content" 38 android:layout_marginLeft="20dp" 39 android:id="@+id/cancelBtn" 40 android:text="取消"/> 41 </LinearLayout> 42 43 </LinearLayout>
2、編寫自定義對話框對應的類,需要繼承Dialog類。這個類我們一般寫在一個單獨的.java文件中。
1 package com.example.myapplication; 2 3 import android.app.Dialog; 4 import android.content.Context; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.view.Window; 8 import android.widget.Button; 9 import android.widget.TextView; 10 11 //定義一個對話框的類,必須繼承Dialog,註意是android.app.Dialog類,不是java.awt.Dialog 12 public class MyDialog extends Dialog { 13 private String msg; //提示信息 14 private TextView msgView; //提示消息控制項 15 private Button okBtn; //確定按鈕 16 private Button cancelBtn; //取消按鈕 17 18 //構造函數 19 public MyDialog(Context context,String msg){ 20 super(context); //必須要調用基類的這個構造函數,必須要Context的形參 21 this.msg=msg; 22 } 23 24 //必須重寫onCreate()方法 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 super.onCreate(savedInstanceState); //自帶的,不能預設 28 requestWindowFeature(Window.FEATURE_NO_TITLE); //去掉預設的標題 29 setContentView(R.layout.my_dialog); //設置對應的佈局文件 30 31 //成員變數會被這些同名的局部變數屏蔽,當然也可以用其他變數名,無影響 32 TextView msgView=findViewById(R.id.tipInfo); 33 Button okBtn=findViewById(R.id.okBtn); 34 Button cancelBtn=findViewById(R.id.cancelBtn); 35 36 //設置消息內容 37 msgView.setText(msg); 38 39 //為2個按鈕設置事件監聽 40 okBtn.setOnClickListener(new View.OnClickListener() { 41 @Override 42 public void onClick(View v) { 43 //......... 44 } 45 }); 46 cancelBtn.setOnClickListener(new View.OnClickListener() { 47 @Override 48 public void onClick(View v) { 49 //...... 50 } 51 }); 52 53 } 54 55 //操作本類成員的方法,比如setXxx()、getXxx()。當然不寫也ok,如果不寫,也可以省略大部分的成員變數 56 //...... 57 58 }
3、使用自定義的對話框
1 //在Activity(.java文件)中使用自定義的對話框 2 MyDialog myDialog=new MyDialog(this,"確定退出嗎?"); 3 myDialog.show(); //這是繼承自基類的方法,可直接用