需要使用Dialog的setView方法,因此
1、编写布局文件
2、编写代码
dialog_set_password.xml
<?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" > <TextView style="@style/DialogTitle" android:text="@string/setPasswordTitle" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" android:inputType="textPassword" /> <EditText android:id="@+id/et_password_confirm" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请再次输入密码" android:inputType="textPassword" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btn_ok" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="确定" /> <Button android:id="@+id/btn_cancle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="取消" /> </LinearLayout> </LinearLayout>
java代码:
/** * 设置密码的弹窗 */ private void showPasswordSetDialog(){ AlertDialog.Builder builder=new AlertDialog.Builder(this); final AlertDialog dialog=builder.create(); View view=View.inflate(this, R.layout.dialog_set_password, null); //dialog.setView(view); dialog.setView(view, 0, 0, 0, 0);//设置边距为0,保证在2.x的版本上运行没问题 final EditText etPassword=(EditText) view.findViewById(R.id.et_password); final EditText etPasswordConfirm=(EditText) view.findViewById(R.id.et_password_confirm); Button btOk=(Button) view.findViewById(R.id.btn_ok); btOk.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String password=etPassword.getText().toString(); String passwordConfirm=etPasswordConfirm.getText().toString(); if(!TextUtils.isEmpty(password)&&!TextUtils.isEmpty(passwordConfirm)){ if(password.equals(passwordConfirm)){ mpref.edit().putString("password", MD5Utils.encode(password)).commit(); Toast.makeText(HomeActivity.this, "密码设置成功!", Toast.LENGTH_SHORT).show(); dialog.dismiss(); }else{ Toast.makeText(HomeActivity.this, "两次密码不一致!", Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(HomeActivity.this, "密码不能为空!", Toast.LENGTH_SHORT).show(); } } }); Button btCancle=(Button) view.findViewById(R.id.btn_cancle); btCancle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //隐藏弹出框 dialog.dismiss(); } }); dialog.show(); }
重要代码:
AlertDialog.Builder builder=new AlertDialog.Builder(this); final AlertDialog dialog=builder.create(); View view=View.inflate(this, R.layout.dialog_set_password, null); //dialog.setView(view); dialog.setView(view, 0, 0, 0, 0);//设置边距为0,保证在2.x的版本上运行没问题