Android 创建警报对话框生成时出错
我正在尝试在“活动”中创建警报对话框生成器。但由于某种原因,当我在AlertDialog.Builder(this)中使用它时,它无法识别“this”对象。 即使我将其更改为GetApplicationContext()或getApplication(),应用程序也会崩溃。 这是我的代码:Android 创建警报对话框生成时出错,android,Android,我正在尝试在“活动”中创建警报对话框生成器。但由于某种原因,当我在AlertDialog.Builder(this)中使用它时,它无法识别“this”对象。 即使我将其更改为GetApplicationContext()或getApplication(),应用程序也会崩溃。 这是我的代码: new AlertDialog.Builder(this) .setTitle("Date Error!") .setMessa
new AlertDialog.Builder(this)
.setTitle("Date Error!")
.setMessage("Date is not valid! Please select another date")
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.error_32)
.show();
我假设您的代码看起来有点像这样:
class AlertClass extends Activity {
...setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
new AlertDialog.Builder(...
}
});
}
照办
new AlertDialog.Builder(AlertClass.this);
AlertDialog.Builder
需要活动上下文,因此getApplicationContext()
和getApplication()
不起作用。您发布的代码显然不直接在活动中。如果它位于片段中,请使用getActivity()
。如果没有,您需要发布更多的周围代码。您需要一个as参数到构造函数。阅读更多关于