問題描述
我創(chuàng)建了一個(gè)自定義對(duì)話框,我想在單擊確定"時(shí)開始一個(gè)新活動(dòng).如何獲取上下文以將其設(shè)置為 Intent 構(gòu)造函數(shù)的第一個(gè)參數(shù)?
I created a custom dialog and I'd like to start a new activity when OK is clicked. How can I get the context to set it as first argument of my Intent constructor?
我可以使用 getContext()
創(chuàng)建意圖,但我不能調(diào)用 startActivity
.我應(yīng)該將調(diào)用對(duì)話框的活動(dòng)傳遞給對(duì)話框的構(gòu)造函數(shù)嗎?是否是通過單擊對(duì)話框來啟動(dòng)活動(dòng)的常用方式?
I can create the intent using getContext()
, but I can't call startActivity
. Shall I pass the activity calling the dialog to the dialog's constructor? Is it the usual way to start an activity by clicking a dialog?
public class CustomDialog extends Dialog implements OnClickListener {
Button okButton, cancelButton;
public CustomDialog(Context context) {
super(context);
setContentView(R.layout.custom_dialog);
okButton = (Button) findViewById(R.id.button_ok);
okButton.setOnClickListener(this);
cancelButton = (Button) findViewById(R.id.button_cancel);
cancelButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == cancelButton)
dismiss();
else {
Intent i = new Intent(getContext(), ItemSelection.class);
startActivity(i); //The method startActivity(Intent) is undefined for the type CustomDialog
}
}
}
推薦答案
public class CustomDialog extends Dialog implements OnClickListener {
Button okButton, cancelButton;
Activity mActivity;
public CustomDialog(Activity activity) {
super(activity);
mActivity = activity;
setContentView(R.layout.custom_dialog);
okButton = (Button) findViewById(R.id.button_ok);
okButton.setOnClickListener(this);
cancelButton = (Button) findViewById(R.id.button_cancel);
cancelButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == cancelButton)
dismiss();
else {
Intent i = new Intent(mActivity, ItemSelection.class);
mActivity.startActivity(i);
}
}
}
這篇關(guān)于如何從 Android 中的對(duì)話框啟動(dòng) Activity的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!