Friday, July 20, 2012

AlertDialog With CheckBox


MyClass.java

AlertDialog.Builder alert = new AlertDialog.Builder(OfferPager.this);
        LayoutInflater adbInflater = LayoutInflater.from(OfferPager.this);
        View checkboxLayout = adbInflater.inflate(R.layout.offer_chk, null);
        dontShowAgain = (CheckBox)checkboxLayout.findViewById(R.id.skip);
        alert.setView(checkboxLayout);
        alert.setTitle("Alert");
        alert.setIcon(android.R.drawable.ic_dialog_alert);
        alert.setMessage(getString(R.string.msg));
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
              public void onClick(DialogInterface dialog, int which) {
                  boolean checkBoxResult = false;
                  if (dontShowAgain.isChecked())  checkBoxResult = true;
                      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                      SharedPreferences.Editor editor = settings.edit();
                      editor.putBoolean("skipMessage", checkBoxResult);   
                      editor.commit();
                  return; 
              } });
       
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, int which) {
              boolean checkBoxResult = false;
              if (dontShowAgain.isChecked())  checkBoxResult = true;
              SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                  SharedPreferences.Editor editor = settings.edit();
                  editor.putBoolean("skipMessage", checkBoxResult);
                  editor.commit();
                  return; 
          } });
       
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean skipMessage = settings.getBoolean("skipMessage", false);
       
        if (!skipMessage )alert.show();



view_chk.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="horizontal"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >
   
    <CheckBox
        android:id="@+id/skip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/offer_dont_display" >
    </CheckBox>

</LinearLayout>

2 comments:

  1. Thanks. all the other examples I can find show how to do a list of checkboxes but this is the only one I could find that shows how to do a single.

    ReplyDelete
  2. Thanks for this example. Very useful. +1up

    ReplyDelete