Android how to make View highlight when clicked?

2019-01-30 11:12发布

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?

5条回答
霸刀☆藐视天下
2楼-- · 2019-01-30 11:34

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

查看更多
我只想做你的唯一
3楼-- · 2019-01-30 11:42

if you still have a problem with that then please remember that some of UI elements are not clickable (RelativeLayout), so you have to add one more line:

<RelativeLayout 
    ....
    android:clickable="true"
    ...
查看更多
爷的心禁止访问
4楼-- · 2019-01-30 11:44

This might be a good place to start looking.

Although, i would advise you to use the ListView itself, rather than implementing it again.

查看更多
Deceive 欺骗
5楼-- · 2019-01-30 11:56

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"
/>
查看更多
Fickle 薄情
6楼-- · 2019-01-30 11:56

To your listview set property

android:listSelector="@color/test"

and this test color set any transparent color you like. you can create any transparent color by using hex transparent color

查看更多
登录 后发表回答