2017-10-17 135 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

標題和消息不起作用時,按鈕和複選框會消失。所以請以你的方式修改佈局。 –