无法解析符号(上下文)
cannot resolve symbol(context)
android 还很年轻。我在代码的这一行收到此错误:new AlertDialog.Builder(context)
。我得到的错误是 cannot resolve symbol(context
).
请帮忙,
case R.id.chk_clas1:
//do stuff
if (chk_clas1.isChecked()) {
if(c1.equals("0")){
adddate(txt_clas1);}
clas="1";
fdate=txt_clas1.getText().toString();
new AlertDialog.Builder(context)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else {
txt_clas1.setText("");
}
在这里,你使用上下文作为变量,但你既没有声明它,也没有初始化它,因此出现错误。
你可以定义它(同时初始化)
Context context = this;
因为 this 指的是 class 的当前对象实例,而 Activity 是一个上下文。
如果你扩展 activity 而不是使用
new AlertDialog.Builder(this)
如果你扩展片段而不是使用
new AlertDialog.Builder(getActivity())
而不是 context
使用 yourActivity.this
因为 context
在我的案例中是当前 class 实例
我的 Activity 是 MainActivity
所以我将使用 MainActivity.this
new AlertDialog.Builder(MainActivity.this)
试试这个, 用 classname.this
替换上下文