java - 当我长按 GridView 中的项目时,如何在 Android 应用程序上显示对话框?

标签 java android gridview onlongclicklistener

当我长按 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/

相关文章:

android - 找不到生命周期 :common-java8 library

android - 如何在Android中将网格子项的绘制方向更改为Right_To_Left

c# - 如何根据提供的数据将数据显示到gridview中?

java - 如何创建属于接口(interface)的实例并实现它

java - 如何通过 char[] 比较构造中的字符串

java - Swing 到 SWT 转换 : which disadvantages?

asp.net - 在 ASP.NET GridView 中使用 DataKeyNames?

java - 程序循环而不运行完整代码

java - 如何在 Qt for android 中保持屏幕打开?

android - 在 React Native 中添加分享操作