当用户在另一个班级的AlertDialog
中选择退出选项时,我正在尝试完成我的活动。但是,当我尝试使用getApplicationContext()
时,我收到此错误
The method getApplicationContext() is undefined for the type new DialogInterface.OnClickListener(){}
和错误
The method startActivity(Intent) is undefined for the type new DialogInterface.OnClickListener(){}
代表StartActivity(intent)
。任何建议都会很棒。感谢
new AlertDialog.Builder(context)
.setTitle("End Option ")
.setMessage("Continue ?")
.setPositiveButton("Quit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}).setNegativeButton("Retry",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
}}).show();
答案 0 :(得分:0)
您需要附加Activity
以启动另一个Context
,然后将Builder
传递给Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
context.startActivity(intent);
中使用内容变量的getContext
:
Intent i = new Intent(getContext(), MainActivity.class);
getContext().startActivity(i);
您还可以通过{{1}}方法获取上下文:
{{1}}
答案 1 :(得分:0)
将意图写入类似的方法
public void anotheractivity()
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
并从警告框中调用它们,
new AlertDialog.Builder(this)
.setTitle("End Option ")
.setMessage("Continue ?")
.setPositiveButton("Quit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
//call the method here
anotheractivity();
}).setNegativeButton("Retry",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
}}).create().show();