您的位置:首页 > 其它

自定义对话框AlertDialog

2016-05-21 14:04 211 查看

步骤:

1.创建自定义对话框布局文件
2.创建AlertDialog对话框
3.代码中得到自定义对话框布局文件的View对象,并将View对象设置给对话框

代码:

自定义对话框布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dip"
android:layout_height="300dip"
android:orientation="vertical"
android:background="#ffffff" >

<TextView
android:layout_width="match_parent"
android:layout_height="45dip"
android:background="#8800ff00"
android:gravity="center"
android:text="请设置密码"
android:textSize="18sp" />

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:id="@+id/et_password"
/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
>
<Button
android:layout_width="140dip"
android:layout_height="wrap_content"
android:text="确定"
android:id="@+id/btn_ok"
android:background="@drawable/function_greenbutton_normal"
/>
<Button
android:layout_width="140dip"
android:layout_height="wrap_content"
android:text="取消"
android:id="@+id/btn_cancel"
android:background="@drawable/function_greenbutton_normal"
/>

</LinearLayout>

</LinearLayout>

使用布局文件创建对话框

AlertDialog.Builder builder = new Builder(this);
//获取自定义对话框布局
View view = View.inflate(this, R.layout.setup_enter_password_view, null);
//获取自定义对话框中的控件进行相应的处理
et_password = (EditText) view.findViewById(R.id.et_password);
btn_ok = (Button) view.findViewById(R.id.btn_ok);
btn_cancel = (Button) view.findViewById(R.id.btn_cancel);

btn_ok.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String password = et_password.getText().toString().trim();
}
});

btn_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ad.dismiss();//关闭对话框
}
});
//创建对话框
ad = builder.create();
//将布局设置到对话框上
ad.setView(view, 0, 0, 0, 0);
//显示对话框
ad.show();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息