Как создать диалоговое окно с предупреждением на основе моего HashMap в Android Studio? - PullRequest
0 голосов
/ 07 ноября 2019

Я пытаюсь отобразить набор вопросов, основываясь на значениях их ключей, которые являются целыми числами 1-6, сначала я бы сгенерировал случайное число, а затем отобразил вопрос, соответствующий этому числу, в диалоговом окне с простым ответом:«ОК», чтобы закрыть диалоговое окно. Я пытался реализовать простой диалог предупреждений, но они слишком запутаны для меня.

public void roll_the_dice(View view){

    HashMap dbreaker = new HashMap();
    dbreaker.put(1, "If you could go anywhere in the world, where would you go?");
    dbreaker.put(2, "If you were stranded on a desert island, what three things would you want to take with you?");
    dbreaker.put(3, "If you could eat only one food for the rest of your life, what would that be?");
    dbreaker.put(4, "If you won a million dollars, what is the first thing you would buy?");
    dbreaker.put(5, "If you could spaned the day with one fictional character, who would it be?");
    dbreaker.put(6, "If you found a magic lantern and a genie gave you three wishes, what would you wish?");

    Random r = new Random();
    int dbreakerNo = r.nextInt((6-1) + 1) + 1;


}

1 Ответ

0 голосов
/ 08 ноября 2019

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnDice = findViewById(R.id.btn_dice);
    btnDice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showAlertDialog(getRandomQuotation());

        }
    });

}

private void showAlertDialog(String quoatationToShow) {
    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
    alertDialog.setTitle("Roll alert");
    alertDialog.setMessage(quoatationToShow);
    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alertDialog.show();
}

private String getRandomQuotation() {

    HashMap<Integer, String> dbreaker = new HashMap();
    dbreaker.put(1, "If you could go anywhere in the world, where would you go?");
    dbreaker.put(2, "If you were stranded on a desert island, what three things would you want to take with you?");
    dbreaker.put(3, "If you could eat only one food for the rest of your life, what would that be?");
    dbreaker.put(4, "If you won a million dollars, what is the first thing you would buy?");
    dbreaker.put(5, "If you could spaned the day with one fictional character, who would it be?");
    dbreaker.put(6, "If you found a magic lantern and a genie gave you three wishes, what would you wish?");

    Random r = new Random();
    int dbreakerNo = r.nextInt((6 - 1) + 1) + 1;
    return dbreaker.get(dbreakerNo);
}

}

activity_main.xml <- это ваш макет </p>

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_dice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Roll the dice!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...