首页 > 代码库 > Android自定义对话框

Android自定义对话框

首先需要一个Layout界面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText android:layout_width="match_parent" android:layout_height="wrap_content" 
        android:hint="姓名" android:id="@+id/alert_homephone_nameEt"/>
    
    <EditText android:layout_width="match_parent" android:layout_marginTop="12dp" android:layout_height="wrap_content"
        android:hint="手机号码" android:id="@+id/alert_homephone_phoneEt"
        />
	
</LinearLayout>

这个界面是我们用来自定义对话框时需要显示的界面。

 AlertDialog.Builder builder =new AlertDialog.Builder(this);
	     
	     LayoutInflater inflater = getLayoutInflater();
	     View layout = inflater.inflate(R.layout.home_phone, null);
	     builder.setView(layout);
	      homePhoneNameEt = (EditText)layout.findViewById(R.id.alert_homephone_nameEt);
	      homePhoneEt = (EditText)layout.findViewById(R.id.alert_homephone_phoneEt);
	      homePhoneEt.setText("13195338922");
		 homePhoneNameEt.setText("老王");
	     builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
	     builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            
	    	 @Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					
				}
	        });
 builder.show();
	    

注意,最后不要忘了show().

总结:方法就是自定义一个layout。然后用layoutInflater进行填充,然后使用AlertDialog.Builder的setView()方法进行指定。然后调用show(),注意show()方法的API说明:

Creates a AlertDialog with the arguments supplied to this builder andDialog.show()‘s the dialog.也就是说创建一个Dialog然后显示


Android自定义对话框