当我长按 GridView 中的某个项目时,我尝试显示一个对话框。我已经尝试过这个,但它抛出错误。我真的不明白如何使用 OnItemLongClickListener 以及为什么它返回 boolean 值。有人可以帮助我更多地理解这一点并弄清楚如何显示此对话框。
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
FavoriteViewDialog dialog =
new FavoriteViewDialog(FavoriteView.this, null, null);
dialog.show();
return true;
}
});
谢谢。
它抛出的错误是......
Thread [<1> main] (Suspended (exception WindowManager$BadTokenException))
FavoriteViewDialog(Dialog).show() line: 245
FavoriteView$2.onItemLongClick(AdapterView, View, int, long) line: 39
GridView(AbsListView).performLongPress(View, int, long) line: 1753
AbsListView.access$600(AbsListView, View, int, long) line: 72
AbsListView$CheckForLongPress.run() line: 1711
ViewRoot(Handler).handleCallback(Message) line: 587
ViewRoot(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4627
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 868
ZygoteInit.main(String[]) line: 626
NativeStart.main(String[]) line: not available [native method]
最佳答案
尝试使用 Activity 的 showDialog(int i) 方法显示对话框:http://developer.android.com/guide/topics/ui/dialogs.html
定义 onCreateDialog(int) 和 onPrepareDialog(int, Dialog) 回调方法的最佳方法是使用 switch 语句来检查传递到方法中的 id 参数...
static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;
然后,为每个 ID 定义带有 switch case 的 onCreateDialog(int) 回调:
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case DIALOG_PAUSED_ID:
// do the work to define the pause Dialog
break;
case DIALOG_GAMEOVER_ID:
// do the work to define the game over Dialog
break;
default:
dialog = null;
}
return dialog;
}
注意:在此示例中,case 语句内没有代码,因为定义对话框的过程超出了本节的范围。请参阅下面有关创建 AlertDialog 的部分,其中提供了适合此示例的代码。
然后调用showDialog(DIALOG_PAUSED_ID); //or another int representing a Dialog.
关于java - 当我长按 GridView 中的项目时,如何在 Android 应用程序上显示对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6601373/