Search code examples
androidlistviewcustom-lists

Adding a listener to a view makes the listview item unclickable


I'm trying to make a custom list. In the list adapter, I've implemented this code in the getView(..) method:

        final RelativeLayout layout = (RelativeLayout) row.findViewById(R.id.layout_main);

        layout.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                switch (event.getAction())
                    {
                        case MotionEvent.ACTION_DOWN:
                        {
                            layout.setBackgroundColor(context.getResources().getColor(R.color.asia_red_color));
                            return true;
                        }

                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                        {
                            layout.setBackgroundColor(context.getResources().getColor(R.color.white));
                            return true;
                        }
                    }

                return false;
            }
        });

Note that the listener that I've implemented prevents/overrides executing the onItemClickListener that I've implemented in MainActivity.

Any solutions?


Solution

  • Have just OnItemClickListener

    Define a selector

    bkg.xml in drawable folder

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

    set the selector to listview. To the custom layout android:background="@drawable/bkg"

    Define colors in color.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="white">#FFFFFF</color>
        <color name="yellow">#FFFF00</color>
    </resources>
    

    Also check if your lsitview row items has buttons. When you click the button may take focus.