[英]How to display a Dialog inside a View?
我是 android 編程的新手,對於第一個程序,我試圖做一個簡單的 Pong-Clone。 我的程序是由不同的操作方法和我自己能夠處理的一點點拼接在一起的。
基線:當我按下“播放”按鈕時,它會調用我的“GameActivity”,將我的“GameView”設置為它的 ContentView。 在 GameView 中,我處理游戲中的所有內容,球的彈跳,玩家和敵人。 但我的問題是一旦一名球員獲勝,如何擺脫困境。
起初我只想調用一個對話框,詢問玩家是否想再次玩游戲或返回菜單,但我當然不能做任何與活動相關的事情,因為我在“游戲視圖”中。 如果我嘗試,它總是告訴我我不能,因為“不能從靜態上下文中引用非靜態方法”。
所以我的 GameActivity 很簡單:
public class GameActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
}
起初我只是把這樣的東西放到我的視圖中:
InfoDialog infoDialog = new InfoDialog();
infoDialog.show(getSupportFragmentManager(), "infoDialog");
但正如我所說,據我所知,我不能在 View 中做到這一點。
TLDR:如何停止或更改我的 Activity 中的 ContentView 或調用該視圖內的對話框?
就像我說的,我對 Android 編程很陌生,如果我這樣做的方式非常復雜,我很抱歉。
您可以在 GameView 構造函數中保存此活動的上下文並在需要時使用它:
class GameView extends View {
private Context mContext;
//Constructor
public GameView (Context context) {
super(context);
mContext = context
}
//Can be called inside the view
public ShowDialog() {
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.