一次开发中,在给一个Textiew设置background为?android:attr/selectableItemBackgroundBorderless时,发现没效果,简化后的布局如下代码:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:gravity="center_horizontal"
android:text="测试点击效果" />
</FrameLayout>
</FrameLayout>
经过一番研究,把上面的代码改成了下面的布局,去掉了一个背景色,结果可以了,如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:gravity="center_horizontal"
android:text="测试点击效果" />
</FrameLayout>
</FrameLayout>
进一步探索,在原基础上给TextView的父亲设上一个背景,结果也可以,代码如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:gravity="center_horizontal"
android:text="测试点击效果" />
</FrameLayout>
</FrameLayout>
......
经过几番探索后,得出一个结论,设置selectableItemBackgroundBorderless后,会从孩子往父亲找一个依附的色。对于我遇到的问题,就是因为TextView往上找的时候,亲生父亲没背景色,然后继续找到了最顶端的爷爷,这个时候才绘制。然而,父亲的兄弟又绘制了颜色,且盖住了最顶端的绘制,导致看不到效果。如果把#ffffff改成#ddffffff,有一定的透明度,结果就显而易见了。
特别注意:当把硬件加速给关闭时,这个效果是没有的。