简体   繁体   中英

Android How to get position of selected item from gridview without using onclicklistner, using ontouchlistner instead

I have a gridview, I need to do stuff on motioneven.action_down and do something for motioneven.action_up ... using onclicklistener is great but does not give me this needed functionality.

Is there anyway to easily call the gridview and get its selected item in a ontouchlistener ? I've been having limited success with making my own implementation. Its hard to get the right x,y because if i call the child it gives me the x and y relative to the child so a button would be 0,0 to 48,48 but it does not tell you the actual location on the screen relative to the gridview or the screen itself.

this is what i've been doing, its partially working so far.

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;
            }
        });

use onItemClickListener to get particular item of a grid view.

    @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

    }

Try it. It works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM