需求:点击GridView中的条目弹出AlertDialog询问用户操作
代码:
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
AlertDialog dialog = new AlertDialog.Builder(XXXXActivity.this)
.setTitle(getString(R.string.prompt))
.setCancelable(false)
.setMessage(getText(R.string.really_preview_program))
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create();
dialog.show();
}
});
问题:
02-26 15:07:16.064 8946-8946/xxx.xxx.xxx.xxx E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@418a5de8 is not valid; is your activity running?
分析:
Context传递错误,原因在于当前Activity所在的tabhost还有更上层的Activity。
解决方案:
创建Dialog时候使用:
AlertDialog dialog = new AlertDialog.Builder(XXXXActivity.this.getParent())