java - Android如何在不使用onclicklistener的情况下从gridview获取所选项目的位置,而是使用ontouchlistener

标签 java android gridview listener

我有一个 gridview,我需要在 motioneven.action_down 上做一些事情并为 motioneven.action_up 做一些事情......使用 onclicklistener 很棒,但没有给我这个需要的功能。

有没有办法轻松地调用 gridview 并在 ontouchlistener 中获取其选定的项目?我在自己实现方面取得的成功有限。很难得到正确的 x,y,因为如果我给 child 打电话,它会给我相对于 child 的 x 和 y,所以按钮会是 0,0 到 48,48,但它不会告诉你屏幕上的实际位置相对于 gridview 或屏幕本身。

这就是我一直在做的事情,到目前为止它部分起作用了。

Grid.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    int x = (int)event.getX();
                    int y = (int)event.getY();
                    int position = 0;
                    int childCount = Grid.getChildCount();

                    Message msg = new Message();
                    Rect ButtonRect = new Rect();
                    Grid.getChildAt(0).getDrawingRect(ButtonRect); 
                    int InitialLeft = ButtonRect.left + 10;
                    ButtonRect.offsetTo(InitialLeft, ButtonRect.top);
                    //

                    while(position < childCount){
                        if(ButtonRect.contains(x,y)){break;}
                        if(ButtonRect.right + ButtonRect.width() > Grid.getWidth())
                        { ButtonRect.offsetTo(InitialLeft, ButtonRect.bottom);}
                        position++;
                        ButtonRect.offsetTo(ButtonRect.right, ButtonRect.top);

                    }

                    msg.what = position;
                    msg.arg1 = ButtonRect.bottom;
                    msg.arg2 = y;
                    cHandler.sendMessage(msg);
                }// end if action up

                if (event.getAction() == MotionEvent.ACTION_UP) {
                }
                return false;
            }
        });

最佳答案

使用 onItemClickListener 获取 GridView 的特定项目。

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub

        // here arg2 is the position of the grid view item on which you have clicked on

    }

尝试一下。它对我有用。

关于java - Android如何在不使用onclicklistener的情况下从gridview获取所选项目的位置,而是使用ontouchlistener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4953270/

相关文章:

c# - ASP Grid View,预定义行高大小

Android 慢 GridView

asp.net - 如何在 GridView 中隐藏 TemplateField 列

基于 Java Tile 的光照性能问题

java - 使用正则表达式从 json 路径中提取多个标记

java - 我无法使用我创建的内部类中的外部类中的数据

android - 为自定义对话框设置 contentDescription

android - 如何在按钮 View 上启用触觉反馈

java - 第一次连接失败后套接字无法连接

android - 如何创建像您在一些 Android 应用程序和 ICS 中看到的帮助叠加层?