gpt4 book ai didi

android - 样式的 CardBackgroundColor 在 CardView 上不起作用

转载 作者:行者123 更新时间:2023-12-05 00:19:02 26 4
gpt4 key购买 nike

我无法弄清楚为什么我的 CardView 没有获得我的样式设置的背景颜色。根据this answer on another StackOverflow question here使用旧的 AndroidSupport-library,您应该可以通过将其添加到默认 AppTheme 来设置它:

<item name="cardBackgroundColor">#ff00ab</item>
但是,这对我来说不会以任何方式改变颜色。一般通过 app:cardBackgroundColor="..."设置颜色工作正常,但对于我的应用程序,我需要它来处理样式。
我还使用一个新项目对其进行了测试,并仅添加了使其工作的最少步骤,但它仍然没有样式设置的卡片颜色...
这是我的 activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="testing string"/>

</androidx.cardview.widget.CardView>
</RelativeLayout>
在我的 styles.xml我已将上面的简单行添加到默认的 Base 应用程序主题中。
感谢您帮助解决我的问题!
编辑:
AppTheme 只是上面添加的行的默认 AppTheme。它最终看起来像这样:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="cardBackgroundColor">#ff00ab</item>
</style>

最佳答案

对我来说,您发布的内容适用于 API 19 和 22,但不适用于 API 28。以下内容适用于所有 API 级别:
而不是定义cardBackgroundColor在您应用的主题中,改为定义 cardViewStyle .这是应用于所有 CardView 的“默认”样式(除非被布局文件中的 style 属性显式覆盖)。

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
...
<item name="cardViewStyle">@style/MyCardViewStyle</item>
</style>

<style name="MyCardViewStyle">
<item name="cardBackgroundColor">#ff00ab</item>
</style>
您可以通过检查其源代码来确定小部件是否支持默认样式属性。将有一个如下所示的构造函数:
public CardView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.cardViewStyle);
}
这里,第三个参数是 R.attr.cardViewStyle ,所以我们知道这就是我们的主题应该定义的。对于不支持默认样式的组件,第三个参数将为 0反而。

关于android - 样式的 CardBackgroundColor 在 CardView 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64900315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com