2012-03-03 8 views
18

Я пытаюсь создать диалоговое окно «подсказка», которое информирует пользователя о включении GPS на своем телефоне, уменьшит время автономной работы. Я хочу, чтобы он всплывал, но имеет флажок, который говорит: «Не спрашивайте меня снова».Как открыть всплывающее окно диалога «Не спрашивайте меня снова»? Android

Как мне создать это на Android?

Спасибо,

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!"); 
+1

Что вы пытались? –

+0

Только что отредактировал главный вопрос. Я добавил, что ^^, но как я могу сделать так, чтобы я мог добавить флажок «Не спрашивать меня снова»? И это на самом деле не показывает? – Zukky

ответ

40

EDIT: Осторожно! Дублирование кода вперед. Поскольку я больше не разрабатываю Android, я не могу реорганизовать код ниже.

Он устанавливает значение в настройках Android и проверяет его, будет ли оно отображать диалоговое окно или нет.

checkbox.xml ресурсов/макеты

<?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.

+0

Нет, это не работает. Так много ошибок. Я следовал этому прекрасно, даже скопировал, вставил и работал с ним. Все еще не работает. Кто-нибудь знает какие-либо другие способы? – Zukky

+0

@ Zukky Я добавил код и макет XML из ранее связанного сайта. Также включен скриншот. Это было протестировано в Android 2.2. Надеюсь, поможет. –

+0

Как примечание, возможно, вы пытались использовать 'checkbox.xml' с именами нижних регистров. Это не сработает, однако Eclipse или любая другая среда IDE показывают, что они находятся в недействительных случаях. –

7

Вы должны будете сделать пользовательский диалог, например AlertDialog, на котором установлен вид пользовательского контента (с setView()). Этот пользовательский макет может быть TextView (для представления информации) + a CheckBoxDo not ask me again). В OnClickListener, установленном для кнопки диалога, вы получите состояние этого CheckBox, и если пользователь проверил его, чем вы установили флаг в настройках (например, значение boolean).

В следующий раз, когда пользователь использует приложение, вы проверите это логическое значение из настроек и, если оно установлено в true, вы не увидите диалоговое окно, иначе пользователь не проверил CheckBox, чтобы вы показали ему диалог еще раз.

Редактировать приложение образец:

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

И макет для содержания диалога (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> 
+0

А, я понимаю. Позвольте мне попробовать, и я вернусь к вам. – Zukky

+0

Можете ли вы показать это в коде? Я не могу получить его на работу. – Zukky

+0

@ Zukky Я сделал образец приложения. Проверьте мой ответ. – Luksprog

2

у меня меньше раствора кода. Это не идеально, потому что описание не может быть использовано, и только информация может быть передана как заголовок диалога. Для этого флажка используется MultiChoiceItem.

в res/values ​​/ strings.XML:

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

Тогда мой код выглядит следующим образом:

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

привет я последовал tutorial и я нашел этот код
вы можете использовать этот код ниже:

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

я имеют ясность и правильный подход по этому вопросу

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

} 

} ``

Смежные вопросы