Search code examples
androidlistviewontouchlistener

Android ListView - getting a number of element in the list in ListView.setOnTouchListener


I'm trying to get the list item number in the onTouch method. That is how i do it:

ListView myList;



...
myList.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    doSomething(myList, event);
                    return false;
                }
            });

...
private void doSomething(ListView myList, MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {                                         
        int first = myList.getFirstVisiblePosition();
        int last = myList.getLastVisiblePosition();
        int itemHeight = myList.getHeight() / (last - first + 1) + myList.getDividerHeight();
        int position = (int)event.getY() / itemHeight;
        View child = myList.getChildAt(position);

...

It seems to be not correct, because sometimes I get wrong position. How can i fix it?


Solution

  • Why don't you set an onTouchListener for the ListView items instead?

    If you're using a custom adapter for your ListView, make it implement OnTouchListener and set setOnTouchListener(this) on your ListView items in the getView(int position, View convertView, ViewGroup parent)-method.

    If you're trying to manipulate the ListView-items, that should do the trick.

    If you're just trying to get the position, use convertView.setOnTouchListener(new OnTouchListener() { ... read position and do something ... } ); in getView(...).

    Update

    If you're just trying to change backgroundcolor/textcolor (imageview content), you can use statelist-drawables.

    For changing textcolor onItemCLick, see this question and answer and set the drawable you created as a textColor for your TextView. For the listitem's backgroundcolor, create a custom listselector (more info, see this question). You can also change the ImageView's content in the same way: create a StateListDrawable and set it as the ImageView's source.