介绍自定义对话框(dialog)的两种方式:
方式一:
首先自定义一个自己想要设计的对话框的界面布局,我的是这样的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#66FF6600"
android:gravity="center"
android:text="请输入密码"
android:textColor="#000000"
android:textSize="22sp" />
<EditText
android:id="@+id/et_input_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:hint="请输入密码"
android:inputType="textPassword" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" >
<Button
android:id="@+id/btn_cancel"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:background="@drawable/button"
android:text="取消" />
<Button
android:id="@+id/btn_confirm"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/button"
android:text="确定" />
</RelativeLayout>
</LinearLayout>
然后在Activity类中进行展示,这里我写了一个showInputPwdDialog方法:
/**
* 输入密码对话框
*/
private void showInputPwdDialog() {
AlertDialog.Builder builder = new Builder(HomeActivity.this);
View view = View.inflate(this, R.layout.dialog_input_pwd, null);
/*
et_input_pwd = (EditText) view.findViewById(R.id.et_input_pwd);
btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
btn_cancel.setOnClickListener(new InputPwdOnClickListener());
btn_confirm.setOnClickListener(new InputPwdOnClickListener());
*/
alertDialog = builder.create();
alertDialog.setView(view, 0, 0, 0, 0);
alertDialog.show();
}
最后,我只想说,是不是很简单!之前一直想不通微信的设置字体大小的对话框是怎么做的,现在恍然大悟啊~
方式二:
可能稍微麻烦一点,主要是通过重写Dialog和使用styles文件实现。
首先编写styles文件,代码如下:
<style name="Dialog_theme" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
</style>
接着重写Dialog:
public class MyDialog extends Dialog {
public MyDialog(Context context, int theme) {
super(context, theme);
}
}
然后创建这么一个方法,便于调用:
private void showMyDialog(Context context, int i) {
MyDialog dialog = new MyDialog(context, i);
dialog.setContentView(自定义弹出框的布局文件);
dialog.show();
}
最后如何使用呢?我想,聪明的你,一定灵光一闪了吧!
showMyDialog(MainActivity.this, R.style.Dialog_theme);
对!就是这样!是不是超级简单
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiYWan5CanVXYs9CX0xWdhZWZk9CX09Wbl9lcvRXakVGa49CXy9GdpRWZoh3LcRXZu5ibkN3Yuc2bsJmLjlGdhR3cvw1LcpDc0RHaiojIsJye.gif)
好了,就这样咯!如有错误,或是不明白的地方,欢迎评论哦,我会及时回答的~~