可能重复:
Dismiss a custom dialog?
我有一个自定义对话框,对话框的布局文件包含一个 id “submit_btn
”的按钮。
在java代码中,我setOnClickListener
到对话框的submit_btn
按钮:
View view = layoutInflater.inflate(R.layout.info_dialog, null);
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
.setView(view)
.create();
infoDialog.show();
Button submitBtn = (Button) view.findViewById(R.id.submit_btn);
submitBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//ERROR: Cannot refer to a non-final variable infoDialog inside an inner class defined in a different method
infoDialog.dismiss();
}
});
然后,当我调用infoDialog.dismiss();
时,Eclipse会引发错误,该错误会引发Cannot refer to a non-final variable infoDialog inside an inner class defined in a different method
。如何根据我的代码摆脱这个问题?
答案 0 :(得分:0)
使用
final AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
.setView(view)
.create();
答案 1 :(得分:0)
你能做到这一点......
final AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
.setView(view)
.create();
// just add final to that line.
或者您可以增加infoDialog的范围。
public class YourActivity {
private AlertDialog mInfoDialog;
private YourMethod() {
View view = layoutInflater.inflate(R.layout.info_dialog, null);
mInfoDialog = new AlertDialog.Builder(MyActivity.this)
.setView(view)
.create();
mInfoDialog.show();
Button submitBtn = (Button) view.findViewById(R.id.submit_btn);
submitBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mInfoDialog.dismiss();
}
});
}
}
答案 2 :(得分:0)
AlertDialog infoDialog = new AlertDialog.Builder(MyActivity.this)
.setView(view)
.setPositiveButton("ok", /*OnClickListenerGoesHere*/)
.create();
将解决您的问题,并在单击按钮时关闭对话框。
答案 3 :(得分:0)
将infoDialog设为类的私有成员,或者将final关键字添加为 final AlertDialog infoDialog = new AlertDialog(...)