19

I am trying to create a "hint" dialog box that informs the user about enabling GPS on their phone will decrease battery life. I want it to pop-up but have a check box that says: "Do not ask me again".

How do I go about creating this in Android?

Thank you,

Zukky.

AlertDialog.Builder prompt = new AlertDialog.Builder(this); 
prompt.setCancelable(false); 
prompt.setTitle("Warning"); 
prompt.setMessage ("HINT: Otherwise, it will use network to find" + 
                   "your location. It's inaccurate but saves on " + 
                   "battery! Switch GPS on for better accuracy " + 
                   "but remember it uses more battery!");
Paolo Colombo
  • 219
  • 5
  • 24
Zukky
  • 237
  • 1
  • 2
  • 8
  • Just edited main question. I added that ^^, but how can I make it so that I can add a "Do not ask me again" checkbox? And it actually doesn't show it? – Zukky Mar 03 '12 at 21:40

5 Answers5

52

EDIT: Beware! Code duplication ahead. Since I'm no longer developing for Android, I can't refactor the code below.

It sets a value in Android Preferences and checks it to whether it will show the dialog or not.

checkbox.xml in resources/layouts

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >
    <CheckBox
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/skip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ok please do not show again." >
    </CheckBox>
</LinearLayout>

Activity.java

public class MyActivity extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile1";
    public CheckBox dontShowAgain;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onResume() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        LayoutInflater adbInflater = LayoutInflater.from(this);
        View eulaLayout = adbInflater.inflate(R.layout.checkbox, null);
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String skipMessage = settings.getString("skipMessage", "NOT checked");

        dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.skip);
        adb.setView(eulaLayout);
        adb.setTitle("Attention");
        adb.setMessage(Html.fromHtml("Zukky, how can I see this then?"));

        adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String checkBoxResult = "NOT checked";

                if (dontShowAgain.isChecked()) {
                    checkBoxResult = "checked";
                }

                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();

                editor.putString("skipMessage", checkBoxResult);
                editor.commit();

                // Do what you want to do on "OK" action

                return;
            }
        });

        adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String checkBoxResult = "NOT checked";

                if (dontShowAgain.isChecked()) {
                    checkBoxResult = "checked";
                }

                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();

                editor.putString("skipMessage", checkBoxResult);                    
                editor.commit();

                // Do what you want to do on "CANCEL" action

                return;
            }
        });

        if (!skipMessage.equals("checked")) {
            adb.show();
        }

        super.onResume();
    }
}

As you can see, I did "copy and paste" too. Changed only the message strings. It works beautifully.

Cengiz Can
  • 1,302
  • 1
  • 15
  • 31
  • Nope it doesn't work. So many errors. I followed this perfectly, even copied and pasted and worked with it. Still not working. Anyone know any other ways? – Zukky Mar 04 '12 at 00:07
  • 1
    @Zukky I added the code and the layout XML from previously linked site. Also included a screenshot. This was tested in Android 2.2. Hope it helps. – Cengiz Can Mar 04 '12 at 01:10
  • 1
    As a side note, maybe you tried to use `checkbox.xml` with lowercase tag names. That won't work, however Eclipse or any other IDE shows that those are in invalid cases. – Cengiz Can Mar 04 '12 at 01:17
  • Haha! I love the way you've done that. Cheers mate, i'll give it a shot tonight ^_^! – Zukky Mar 06 '12 at 13:04
  • @Zukky If it doesn't work then surely your project structure is corrupted. I suggest testing on a new project then seeing how it works. And remember to ACCEPT the answer which you find most satisfying. – Cengiz Can Mar 06 '12 at 23:36
  • 2
    Works perfectly. Except for this: `if (skipMessage != "checked")` Comparing strings with != or == is a huge NO-NO! You should have used `editor.putBoolean("skipMessage", dontShowAgain.isChecked())` instead of `editor.putString("skipMessage", checkBoxResult);`. Or, if you prefer strings, `if (!skipMessage.equals("checked"))` – Bojan Radivojevic Jun 26 '12 at 13:04
8

You'll have to make a custom dialog, for example an AlertDialog on which you set a custom content view(with setView()). That custom layout could be a TextView(to present the information)+ a CheckBox (with Do not ask me again). In the OnClickListener set for the dialog's button you get the state of that CheckBox and if the user checked it than you set a flag in the preferences(boolean value of true, for example).

Next time the user usess the app you'll check that boolean value from the preferences and if it is set to true then you will not show the dialog otherwise the user didn't checked the CheckBox so you show him the dialog again.

Edit sample application:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class DoNotShowDialog extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button action = new Button(this);
        action.setText("Start the dialog if the user didn't checked the "
                + "checkbox or if is the first run of the app.");
        setContentView(action);
        action.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(DoNotShowDialog.this);
                boolean dialog_status = prefs
                        .getBoolean("dialog_status", false);//get the status of the dialog from preferences, if false you ,ust show the dialog
                if (!dialog_status) {
                    View content = getLayoutInflater().inflate(
                            R.layout.dialog_content, null); // inflate the content of the dialog
                    final CheckBox userCheck = (CheckBox) content //the checkbox from that view
                            .findViewById(R.id.check_box1);
                    //build the dialog
                    new AlertDialog.Builder(DoNotShowDialog.this) 
                            .setTitle("Warning")
                            .setView(content)
                            .setPositiveButton("Ok",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            //find our if the user checked the checkbox and put true in the preferences so we don't show the dialog again 
                                            SharedPreferences prefs = PreferenceManager
                                                    .getDefaultSharedPreferences(DoNotShowDialog.this);
                                            SharedPreferences.Editor editor = prefs
                                                    .edit();
                                            editor.putBoolean("dialog_status",
                                                    userCheck.isChecked());
                                            editor.commit();
                                            dialog.dismiss(); //end the dialog.
                                        }
                                    })
                            .setNegativeButton("Cancel",
                                    new DialogInterface.OnClickListener() {

                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            //find our if the user checked the checkbox and put true in the preferences so we don't show the dialog again
                                            SharedPreferences prefs = PreferenceManager
                                                    .getDefaultSharedPreferences(DoNotShowDialog.this);
                                            SharedPreferences.Editor editor = prefs
                                                    .edit();
                                            editor.putBoolean("dialog_status",
                                                    userCheck.isChecked());
                                            editor.commit();
                                            dialog.dismiss();

                                        }
                                    }).show();
                } else {
                    //the preferences value is true so the user did checked the checkbox, so no dialog
                    Toast.makeText(
                            DoNotShowDialog.this,
                            "The user checked the checkbox so we don't show the dialog any more!",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

And the layout for the content of the dialog(R.layout.dialog_content):

<?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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enabling GPS on your phone will decrease battery life!" />

    <CheckBox
        android:id="@+id/check_box1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Do not ask me again!" />

</LinearLayout>
user
  • 86,916
  • 18
  • 197
  • 190
4

I have my less code solution. It's not perfect, because description cannot be used and only information can be passed as a title of the dialog. MultiChoiceItem is used for checkbox.

in res/values/strings.xml :

<string-array name="do_not_show_again_array">
    <item>Do not show again.</item>
</string-array>

Then my code looks as follow:

DialogInterface.OnClickListener dialogClickListener = new OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // Do something here
    }
};
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.setTitle("Title/Description")
        .setMultiChoiceItems(R.array.do_not_show_again_array, null, new OnMultiChoiceClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                appPrefs.setLocationOnStart(!isChecked);
            }
        })
        .setPositiveButton("Ja", dialogClickListener)
        .setNegativeButton("Nein", dialogClickListener).show();
}
Malachiasz
  • 7,126
  • 2
  • 35
  • 49
1

hi i followed a tutorial and i found this code
you can use this code below :

  AlertDialog.Builder adb= new

 AlertDialog.Builder(this);
  LayoutInflater adbInflater = 

 LayoutInflater.from(this);
  View eulaLayout = adbInflater.inflate

 (R.layout.activity_main, null);
  check = (CheckBox)

 eulaLayout.findViewById(R.id.skip);
  adb.setView(eulaLayout);
  adb.setTitle("Example:");
  adb.setMessage(Html.fromHtml("Type your 

  text here: "));
  adb.setPositiveButton("Ok", new

  DialogInterface.OnClickListener() {
        public void onClick(DialogInterface 

 dialog, int which) {
            String checkBoxResult = "NOT 

 checked";
            if (check.isChecked())  

 checkBoxResult = "checked";
              SharedPreferences settings = 

 getSharedPreferences(PREFS_NAME, 0);
              SharedPreferences.Editor 

 editor = settings.edit();
              editor.putString("noshow", 

 checkBoxResult);
              // Commit the edits!

            //  sunnovalthesis();

              editor.commit();
            return;
        } });

       adb.setNegativeButton("Cancel", new

    DialogInterface.OnClickListener() {
    public void onClick(DialogInterface 

     dialog, int which) {
        String checkBoxResult = "NOT 

    checked";
        if (check.isChecked())  

       checkBoxResult = "checked";
        SharedPreferences settings = 

       getSharedPreferences(PREFS_NAME, 0);
          SharedPreferences.Editor editor = 

        settings.edit();
          editor.putString("noshow", 

    checkBoxResult);
          // Commit the edits!

        //  sunnovalthesis();

          editor.commit();
            return;
    } });
     SharedPreferences settings = 

    getSharedPreferences(PREFS_NAME, 0);
  String noshow = settings.getString

     ("noshow", "NOT checked");
      if (noshow != "checked" ) adb.show();
dondondon
  • 881
  • 8
  • 4
1

i have a clarity and right approach for this question

package com.example.user.testing;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;

public class MainActivity extends AppCompatActivity {
CheckBox dontShowAgain;
public static final String PREFS_NAME = "MyPrefsFile1";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final AlertDialog.Builder adb = new             AlertDialog.Builder(MainActivity.this);
    LayoutInflater adbInflater = LayoutInflater.from(MainActivity.this);
    View eulaLayout = adbInflater.inflate(R.layout.checkbox, null);

    dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.skip);
    adb.setView(eulaLayout);
    adb.setTitle("Attention");
    adb.setMessage("Your message here");
    adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {


            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("skipMessage", dontShowAgain.isChecked());
            editor.commit();
            dialog.cancel();
        }
    });

    adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    Boolean skipMessage = settings.getBoolean("skipMessage", false);
    if (skipMessage.equals(false)) {
        adb.show();
    }

}

}``

Rohit Sai
  • 41
  • 3