2014-12-07 2 views
-1

Я создаю игру, в которой пользователь выбирает изображение и создает головоломку. Первый экран позволяет пользователю выбрать изображение, а диалоговое окно отображается щелчком мыши, что позволяет пользователю выбрать сложность. После ImageSelection изображение отображается в течение трех секунд в ShowImage Activity, после чего запускается GamePlay. Я создал диалог следующим образом:Отклонить диалоговое окно перед новой активностью

import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 

class GameDialog { 

    private static Context mContext; 
    private static int difficulty; 
    static AlertDialog d; 

    public static AlertDialog showDifficulties(Context c, final int img_id) { 

     mContext = c; 

     AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 
     builder.setTitle("Select difficulty") 
       .setItems(R.array.my_array, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
        // the 'which' argument contains the index position 
        // of the selected item 

         // default difficulty is 3 
         int difficulty = 3; 

         // options for difficulties 
         switch (which) { 

          // when the user clicks 'easy' 
          case 0: 
           difficulty = 3; 
           System.out.print("DIFFICULTY"); 
           System.out.println("" + difficulty); 

          break; 

          // when the user clicks 'medium' 
          case 1: 
          difficulty = 4; 

          System.out.print("DIFFICULTY"); 
          System.out.println("" + difficulty); 
          break; 

          // when the user clicks 'hard' 
          case 2: 
          difficulty = 5; 

          System.out.print("DIFFICULTY"); 
          System.out.println("" + difficulty); 
          break; 
          } 

         // send intent with image id and difficulty 
         // to ShowImage activity 
         Intent start_game = new Intent(mContext, ShowImage.class); 
         start_game.putExtra("img_id", img_id); 
         start_game.putExtra("difficulty", difficulty); 
         d.dismiss(); 
         mContext.startActivity(start_game); 
       } 
     }); 

     d = builder.create(); 
     return d; 

    } 
} 

Это прошло довольно хорошо (и работало). Во-вторых, в GamePlay я хочу, чтобы пользователь мог изменить сложность в меню, после чего приложение снова запускает ShowImage, но с соответствующей выбранной трудностью. Вот код для Геймплей:

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    // handle item selection 
    switch (item.getItemId()) { 
     case R.id.reset_game: 
      //TODO: resets the game to initial shuffled tiles 
      Intent intent = getIntent(); 
      finish(); 
      startActivity(intent); 

     case R.id.difficulty: 
      // lets user change the difficulty of the game 
      // pass the index to the dialog and show the dialog 
      Dialog d = GameDialog.showDifficulties(GamePlay.this, selected_image); 
      System.out.println(selected_image); 
      d.show(); 

     case R.id.quit: 
      // returns the user to ImageSelection 
      intent = new Intent(GamePlay.this, ImageSelection.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
      finish(); 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 

Однако, приложение выбрасывает ошибку «GamePlay просочилась окно com.android.internal.policy.impl.PhoneWindow $ DecorView (и т.д.), который первоначально был добавлен здесь» Я сделал некоторые исследования и подумал, что это может быть вызвано не закрытием диалога в ActivitySelection Activity. Таким образом, я сделал несколько шагов, и добавил, что это мой ImageSelection активности:

@Override 
public void onPause() 
{ 
    d.dismiss(); 
    super.onPause(); 

} 

Однако это не исправить мою проблему: с Моим вопросом поэтому есть то, что я делаю не так и как это исправить ошибку? Цель состоит в том, чтобы получить тот же диалог (из отдельного класса, который я создал) в двух разных действиях. Спасибо заранее!

Редактировать: Теперь я добавил «d.dismiss();» к классу диалога, предложенному Hany Elsioufy, однако это не устранило проблему.

+0

Сообщения об ошибке упоминается 'PhoneWindow $ DecorView', но я не вижу ни' 'PhoneWindow' ни DecorView' в вашем коде. –

+0

Я честно не знаю, что это значит, потому что я не вижу ничего, что связано с моим кодом. Но когда я его искал, я обнаружил, что это связано с тем, что он не отклоняет диалог. – Nifty

ответ

0

Я исправил его!

Оказывается, я должен был добавить возвращаемое значение в моем выключателе случае в onOptionsItemSelected():

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    // handle item selection 
    switch (item.getItemId()) { 
     case R.id.reset_game: 
      //TODO: resets the game to initial shuffled tiles 
      Intent intent = getIntent(); 
      finish(); 
      startActivity(intent); 
      return true; 

     case R.id.difficulty: 
      // lets user change the difficulty of the game 
      // pass the index to the dialog and show the dialog 
      Dialog d = GameDialog.showDifficulties(GamePlay.this, selected_image); 
      System.out.println(selected_image); 
      d.show(); 
      return true; 

     case R.id.quit: 
      // returns the user to ImageSelection 
      intent = new Intent(GamePlay.this, ImageSelection.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      startActivity(intent); 
      finish(); 
      return true; 

     default: 
      return super.onOptionsItemSelected(item); 

    } 
} 
0

Define AlertDialog d; в качестве переменной экземпляра, а затем перед любым startActivity или Intents записи:

d.dismiss(); 
+0

Не могли бы вы объяснить это дальше? Когда я помещаю это в свой, скажем, GameActivity, я получаю сообщение об ошибке нулевого указателя, потому что он вызывает «увольнение» на то, чего не существует. – Nifty

+0

вы хотите отменить диалог перед тем, как перейти к другому действию, а затем просто объявить AlertDialog d в переменной экземпляра, тогда вы говорите AlertDialog d = builder.create(); замените его на d = builder.create(); затем вызовите d.dismiss(); до началаActivity() способ –

+0

я вижу. Проблема в том, что мой диалог находится в отдельном классе. StartActivity также находится в этом классе, что означает, что я вызываю d.убрать() внутри этого класса, диалог никогда не будет отображаться, когда он вызывается в Activity. Как это исправить? – Nifty

1

@Override общественного логический onOptionsItemSelected (MenuItem пункт) {

// handle item selection 
switch (item.getItemId()) { 
    case R.id.reset_game: 
     //TODO: resets the game to initial shuffled tiles 
     Intent intent = getIntent(); 
     finish(); 
     startActivity(intent); 

    case R.id.difficulty: 
     // lets user change the difficulty of the game 
     // pass the index to the dialog and show the dialog 
     Dialog d = GameDialog.showDifficulties(GamePlay.this, selected_image); 
     System.out.println(selected_image); 
     d.show(); 

    case R.id.quit: 
     // returns the user to ImageSelection 
     intent = new Intent(GamePlay.this, ImageSelection.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(intent); 
     finish(); 
    default: 
     return super.onOptionsItemSelected(item); 
} 

}

В приведенном выше коде, существует не является оператором break. пожалуйста, используйте break заявление когда вы используете кейс переключения.

+0

О! И затем, что я ставлю в onOptionsItemSelected, чтобы вернуться? Потому что я понимаю, что это логическое. – Nifty

+0

добавьте эту строку после возвращения конца ключа super.onOptionsItemSelected (item) – kanivel

+0

Ничего, я нашел решение! Спасибо, что поставил меня на правильный путь. – Nifty

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