无法在 PopupWindow 中执行 GridView 的 OnItemClick

3

我有一个GridView,它显示在弹出窗口中(GridView位于透明布局中,该布局继承自LinearLayout并具有部分透明背景)。 我无法使GridView的OnItemClick执行。 当我点击GridView中的图像时,似乎已被点击(图像背景更改),但是OnItemClick未被调用。

以下是我适配器和包含GridView的弹出视图的代码。 谢谢!

//Adapter

公共类ImageAdapter扩展自BaseAdapter { 私有上下文mContext; 私有int itemBackground;

public ImageAdapter(Context c) {
    mContext = c;

  //---setting the style---
    TypedArray a = c.obtainStyledAttributes(R.styleable.Gallery1);
    itemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
    a.recycle();
}

....

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(mContext);
    } else {
        imageView = (ImageView) convertView;
    }
    imageView.setImageResource(images[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageView.setBackgroundResource(itemBackground);
    return imageView;

}
public Integer[] images = {
        R.drawable.sound1,
        R.drawable.sound2,
        R.drawable.sound3,
        R.drawable.sound4
};

}

//////////In Activity, onCreate////////

...

final LayoutInflater inflater=(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final TransparentLayout musicGrid = (TransparentLayout) inflater.inflate(R.layout.gridviewpopup, null, false);
    final GridView gView = (GridView) musicGrid.findViewById(R.id.music_gridview);
    gView.setAdapter(new ImageAdapter(this));

    final PopupWindow soundSelectorWindow = new PopupWindow(this);
    soundSelectorWindow.setContentView(musicGrid);
    soundSelectorWindow.setTouchable(true);

    gView.setOnItemClickListener(new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
        {   
            //NEVER GETS HERE
            soundSelectorWindow.dismiss();

        }
    }); 
3个回答

3

我无法解释为什么OnItemClickListener不起作用,但当我用OnTouchListener替换时它可以工作。您需要区分哪个项被点击了吗?还是只需知道弹出窗口被单击了即可?从您的代码来看,似乎只需要知道后者,所以使用OnTouch应该可以:

    popup.setTouchable(true);
    popup.setFocusable(true);
    gView.setClickable(true);

    gView.setOnTouchListener(new View.OnTouchListener() 
    {
        public boolean onTouch(View v, MotionEvent event) 
        {   
            popup.dismiss();
            return true;
        }
    }); 

是的,那也行。不过,我需要知道点击了哪个项目。谢谢查看! - k_day

3
如果您删除 soundSelectorWindow.setTouchable(true); 会发生什么?

我制作了一个非常简单的应用程序来演示这种行为,如果有人想要查看: http://dl.dropbox.com/u/257677/SamplePopup.zip - k_day
1
尽管你的例子设计看起来很奇怪,但毕竟它是一个例子。你不需要设置setTouchable - 它默认为true。然而你确实需要设置popup.setFocusable(true)。 - Alex Volovoy
非常感谢你,Alex!那个管用了。我仍然不确定为什么在我的网格视图中可以滚动,而不需要将弹出窗口设置为可聚焦状态,但无法进行选择。 - k_day

1

检查模拟器的虚拟机大小,确保其足够好以在其虚拟机中运行您的应用程序。
检查您的<ApplicationName.apk>大小。将其保持在最小尺寸,以便模拟器在执行您的应用程序时不会遇到任何困难。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接