我指的是https://dev59.com/I2Af5IYBdhLWcg3wmzpL#24475228中的回答。
该回答使用了Android中的可绘制对象:
因此,我想使用自己定义的可绘制对象来实现以下目的:
当我长按卡片项并执行
关于使用android:background的一些注意事项
请注意,当您将
但是,如果您将
该回答使用了Android中的可绘制对象:
?android:attr/selectableItemBackground
。
以下是当我点击卡片时发生的情况。请注意,通过使用来自Android的可绘制对象,android:state_selected="true"
(当setSelected(true)
)将不会产生任何颜色变化效果。因此,我想使用自己定义的可绘制对象来实现以下目的:
- 它看起来更漂亮。
- 能够处理
android:state_selected="true"
。
statelist_item_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/selected_background" />
<item android:state_selected="true" android:drawable="@drawable/selected_background" />
<item android:drawable="@android:color/transparent" />
</selector>
selected_background.xml
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffe1b3" />
<stroke
android:width="1px"
android:color="#fff76d3c" />
</shape>
card_row.xml
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:clickable="true"
android:foreground="@drawable/statelist_item_background"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:padding="5dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_label_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
tools:text="Item Number One" />
<TextView
android:id="@+id/txt_date_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
tools:text="Item Number One" />
</LinearLayout>
</android.support.v7.widget.CardView>
当我长按卡片项并执行
childView.setSelected(true);
时,这是我的结果。
我所有的卡片内容(TextView
)都被阻止了。我该如何避免这种情况?关于使用android:background的一些注意事项
请注意,当您将
android:background="@drawable/statelist_item_background"
与CardView
本身一起使用时,不会发生任何事情。但是,如果您将
android:background="@drawable/statelist_item_background"
与CardView
的LinearLayout
一起使用,您将得到以下不完美的结果。
突出显示的颜色未覆盖整个卡片。
更新
看起来这是CardView
的限制 - https://code.google.com/p/android/issues/detail?id=78198 使用“前景”作为解决方法不是一个选项,因为它会覆盖卡片内容。