Я создаю игру, в которой пользователь выбирает изображение и создает головоломку. Первый экран позволяет пользователю выбрать изображение, а диалоговое окно отображается щелчком мыши, что позволяет пользователю выбрать сложность. После 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, однако это не устранило проблему.
Сообщения об ошибке упоминается 'PhoneWindow $ DecorView', но я не вижу ни' 'PhoneWindow' ни DecorView' в вашем коде. –
Я честно не знаю, что это значит, потому что я не вижу ничего, что связано с моим кодом. Но когда я его искал, я обнаружил, что это связано с тем, что он не отклоняет диалог. – Nifty