Android beginner: Touch events in android gridview

a 夏天 提交于 2019-11-30 10:24:00
PS376

Use the OnTouchListener in this way. Read up on MotionEvent types like ACTION_UP, ACTION_MOVE, and ACTION_DOWN which mean that the key was pressed here, mouse was moved, or key was unpressed here...

public void addListenerToGrid() {
    gridView = (GridView) findViewById(R.id.gridView1);

    gridView.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent me) {

            int action = me.getActionMasked();
            float currentXPosition = me.getX();
            float currentYPosition = me.getY();
            int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition);
                        if (action == MotionEvent.ACTION_UP) {
                            // Key was pressed here
                        }

            return true;

}

Emile

Following on from your code, as jaydeepfifadra suggested you can use the setOnItemClickListener method of the gride view rather than the image itself. (Not to say that that isn't possible but i've not tried it).

gridView.setOnItemClickListener(

    new OnItemClickListener(){
        public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
            ((Image)view.setSelected(!(Image)view.getSelected()));
        }
    });
);

Now i'm not 100% sure if the following will work, but in the above i've set the view.setSelected() state of the image to toggle. I'm sort of guessing that you can set the image resource to a drawable selector. i.e.

make your R.drawable.sample_2 resources selectors, such as:

<?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/image_selected" />

    <item android:drawable="@drawable/image_unselected" />
</selector>

However, whilst this allows you to detect the single tap that would toggle the selected state. It doesn't cover the double tap. There also doesn't appear to be a setOnDoubleClickItemListener() method.

As such it might be required for your specific situation that you implement a GestureDetector and implement your own SimpleOnGestureListener class (MyGestureListener extends SimpleOnGestureListener) that manages the double and single tap events your looking for.

You can see an example of implementing the gesture listener and detector here.

how to implement both ontouch and also onfling in a same listview?

You would set the gestureListener as the onTouchListener of your grid view.

jaydeepfifadra

Use the onItemSelectListener of gridView.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!