Android自定义对话框

本文介绍如何在Android应用中自定义AlertDialog,包括创建布局文件、初始化对话框及设置按钮响应等步骤。

首先需要一个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 and Dialog.show()'s the dialog.也就是说创建一个Dialog然后显示


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值