【发布时间】:2014-08-17 19:36:57
【问题描述】:
简而言之:
我们如何定义 CardView 的 cardBackgroundColor 属性的颜色状态(在这种情况下,在 ListView 布局中)?
(我正在使用 Android L 开发者预览版的 RC1,在安装了 4.4 的手机上,以及 build.gradle 中的“com.android.support:cardview-v7:21.0.0-rc1”)
更长:
在 CardView 布局中,我们通过 cardCornerRadius 和 cardBackgroundColor 设置 CardView 的圆角半径和背景颜色。
但是,背景颜色不反映选定的状态,例如,如果列表项被按下。
如果您在 CardView 的内部视图中设置了背景颜色和相关的状态,它们会受到尊重,但是,它将显示在您在 CardView 中定义的角上。
那么,我们如何确保 CardView 的 cardBackgroundColor 中的状态得到尊重?
这是用于 cardBackgroundColor 的颜色 colour_with_states.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:color="@android:color/holo_green_dark" />
<item android:state_focused="true" android:state_enabled="false" android:color="@android:color/holo_green_dark" />
<item android:state_focused="true" android:state_pressed="true" android:color="@android:color/holo_green_dark" />
<item android:state_focused="false" android:state_pressed="true" android:color="@android:color/holo_green_dark" />
<item android:state_focused="true" android:color="@android:color/holo_green_dark" />
<!-- Only this below is seen in the cardview dispaly -->
<item android:color="@android:color/holo_blue_bright" />
</selector>
以及使用 CardView 的布局:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
cardview:cardCornerRadius="10dp"
cardview:cardBackgroundColor="@color/colour_with_states"
>
<!-- If we set a background color below, it will overwrite our radius defined above -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:text="Lorem ipsum"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItem"
android:background="@null"
android:gravity="center_vertical"
android:paddingTop="8dip"
android:paddingBottom="8dip"
android:paddingStart="8dip"
android:paddingEnd="8dip"
/>
</android.support.v7.widget.CardView>
【问题讨论】:
-
在常规
FrameLayout中使用相同的背景颜色是否尊重所选状态?我认为您在您的CardView上拨打setOnClickListener? -
我认为答案就在您的问题中:
If, in the inner view of the CardView, you set a background colour, and associated states, which are respected, however, it will display over the corners you defined in the CardView.。父 ViewGroup(卡片)正在将焦点和事件路由到子视图。此外,ListView有自己的selector用于突出显示所选项目。 -
@S.D. “路由”不是它的工作方式。你应该测试 android:duplicateParentState。通过这种方式,父级和任何感兴趣的子级都可以使用 XML 选择器隐式响应感兴趣的事件。 CardView 打破了这种模式,无法“听到”父选择状态的变化,可能是因为有问题的属性是特殊的 cardview:cardBackgroundColor,而不是通用的 android:background。
-
希望 [this][1] 可以帮助 [1]:stackoverflow.com/questions/24518376/…