2017-10-17 272 views
0

如何在对话框中放置复选框,如果用户没有选中框,则正面按钮将不起作用,负面按钮将关闭对话框。警报对话框?

这里是我的代码

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(); 
      } 
+0

的可能的复制[警报对话框与文本follwed一个复选框和2个按钮(https://stackoverflow.com/questions/4965294/alert-dialog-with-text-follwed-with-a-checkbox-and- 2按钮) –

+0

用复选框和消息创建一个新的布局,然后在'setPositiveButton'中检查是否勾选复选框。如果选中,则提交true。 –

回答

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> 

下面是视图处理程序。

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。

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

+0

为什么在设置自定义视图时,标题和消息 – osoda

+0

标题和消息不起作用时,按钮和复选框会消失。所以请以你的方式修改布局。 –