警报对话框?

时间:2017-10-17 06:16:10

标签: android alertdialog

如何在对话框中放置一个复选框,如果用户没有选中该框,则肯定按钮将不起作用,而否定按钮将关闭对话框。

这是我的代码

final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            boolean agreed = sharedPreferences.getBoolean("agreed", false);
            if (!agreed) {
                new AlertDialog.Builder(getActivity())
                        .setTitle("License agreement")
                        .setMessage("")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putBoolean("agreed", true);
                                editor.commit();
                            }
                        })
                        .setNegativeButton("No", null)
                        .show();
            }

2 个答案:

答案 0 :(得分:0)

您可以使用您选择的布局和自定义行为(例如已停用的正按钮)构建自定义DialogFragment

以下是一些教程:

答案 1 :(得分:0)

这是一项艰苦的工作。

这是布局(about_us.xml)。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkbox_new"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textStyle="bold"
        android:text="@string/creator_name"
        android:textColor="@color/colorBlack"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"/>

</LinearLayout>

以下是View Handler。

final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean agreed = sharedPreferences.getBoolean("agreed", false);
if (!agreed) {
    View view = getLayoutInflater().inflate(R.layout.about_us, null);
    final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox_new);
    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getApplicationContext());
    alertBuilder.setView(view);
    alertBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
             if (checkBox.isChecked()){
                 SharedPreferences.Editor editor = sharedPreferences.edit();
                 editor.putBoolean("agreed", true);
                 editor.commit();
             }
         }
    });
    alertBuilder.create().show();
}

在此视图处理程序中,我正在检查是否选中了复选框。如果选中,则提交true。

您可以根据需要修改此代码。

相关问题