再表示確認ありのダイアログ

「今後表示しない」などチェックボックスのある確認のダイアログを表示して、
アプリで任意にリセットする処理が実行されなければ、表示しないようにするケース。
以下のようなダイアログのケース

f:id:posturan:20160313225107p:plain



この表示/非表示の制御は、XMLに定義しない Preference を使うと良い。

例)

ダイアログのレイアウト、confirm_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="メッセージ。。。。。"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:orientation="vertical" >
        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp"
            android:layout_marginLeft="10dp"
            android:text="今後表示しない"
            android:textColor="#000000" />
    </LinearLayout>
</LinearLayout>

Preference に格納するキーは、見つけやすいクラス、プロジェクトのポリシーに
沿って、static を定義

public final static String MESSAGE1_DISPLAY = "Message1_display";

ボタンを押したら、表示する例、、、
(この中に、状態の制御の処理を書いてしまう。)

Button displayButton = (Button)findViewById(R.id.testButton);
displayButton.setOnClickListener(new View.OnClickListener(){
   boolean isState;
   @Override
   public void onClick(View v){
      final SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
      boolean message1_display = sharePref.getBoolean(MESSAGE1_DISPLAY, true);
      if (!message1_display) return;

      isState = false;
      LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
      final View dialogView = inflater.inflate(R.layout.confirm_dialog, null);
      CheckBox checkbox = (CheckBox)dialogView.findViewById(R.id.checkBox1);
      checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
         @Override
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
            isState = isChecked;
         }
      });
      // View とボタンとの間に隙間ができるの防ぐ為に、setView を後から実行する
      AlertDialog dialog = new AlertDialog.Builder(SampleActivity.this)
      .setCancelable(false)
      .setPositiveButton("OK", new DialogInterface.OnClickListener(){
         @Override
         public void onClick(DialogInterface dialog, int which){
            sharePref.edit().putBoolean(MESSAGE1_DISPLAY, !isState ).commit();
         }
      }).create();
      dialog.setView(dialogView, 0, 0, 0, 0);
      dialog.show();
   }
});