Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android how to make View highlight when clicked?

I have a linear layout in which each row is inflated programatically and I want the rows to behave like the ListView when clicked on. That is, I want the row to highlight in the exact same way/colour that the default ListView does. How would I go about doing this?

like image 201
Kman Avatar asked Jul 16 '10 08:07

Kman


People also ask

How do you highlight a button when pressed?

You can use OnTouchListener or you can use a selector. button. setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event. getAction() == MotionEvent.


2 Answers

Ok I have finally figured out how to do this...basically it is done using a selector like the color selector linked by style except instead of 'color' use a drawable for the states and you can refer to the default list drawable that is used in ListView by this:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"     android:drawable="@android:drawable/list_selector_background" />       </selector> 

and using this xml as the background for my View.

All the public default drawables can be found here: http://developer.android.com/reference/android/R.drawable.html

like image 78
Kman Avatar answered Sep 20 '22 07:09

Kman


I was able to do the same with a text view that I wanted to behave like a list item by using:

<Textview .... android:background="@android:drawable/list_selector_background" /> 
like image 33
davenpcj Avatar answered Sep 24 '22 07:09

davenpcj