logo头像
Snippet 博客主题

Dialog控件学习

本文于 357 天之前发表,文中内容可能已经过时。

Dialog相关学习


1.如何在点击确定或取消按钮时,不取消弹窗

使用场景:在弹窗输入参数后,需要对参数进行校验是否合法时。如果不规范则提示用户重新输入

使用AlertDialog.Builder创建的Dialog,在调用setPositiveButton相关的按钮时,会自动隐藏弹窗。若不想隐藏则需要再获取一次Button设置监听事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class CustomDialog extends DialogFragment {
private EditText mUserName;
private EditText mPassword;

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = requireActivity().getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = inflater.inflate(R.layout.custom_dialog, null);
mUserName = view.findViewById(R.id.username);
mPassword = view.findViewById(R.id.password);
builder.setView(view).setPositiveButton("确定", null).setNegativeButton("取消", null);
AlertDialog dialog = builder.create();
// 必须调用show方法,否则下面获取到的button为null
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
if (TextUtils.isEmpty(mUserName.getText().toString())) {
Toast.makeText(getActivity(), "用户名为空", Toast.LENGTH_SHORT).show();
return;
} else {
dialog.dismiss();
}
});
return dialog;
}
}

2.DialogFragment在显示时提示Theme错误

1
2
3
4
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:696)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:552)

该问题属于没有给DialogFragment弹窗依赖的Activity没有使用AppCompat的Theme.


解决方案:

  1. 使用的Activity直接继承Activity而不用继承AppCompatActivity
  2. AndroidManifest对应的Activity的主题改为使用AppCompat的主题
1
2
3
4
5
6
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>