首页 > 解决方案 > Android 应用程序在尝试使用 ?attr/variable 时崩溃

问题描述

我正在尝试使用 ?attr/var 来设置颜色,但它一直在崩溃,说列表视图 xml 有错误。如果我使用正常的颜色属性,它可以正常工作。

2021-02-04 18:10:45.621 13812-13812/com.daford.sermonviewer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.viewer, PID: 13812
    android.view.InflateException: Binary XML file line #3 in com.viewer:layout/list_item: Binary XML file line #3 in com.viewer:layout/list_item: Error inflating class android.widget.TextView
    Caused by: android.view.InflateException: Binary XML file line #3 in com.viewer:layout/list_item: Error inflating class android.widget.TextView

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="textColor" format="color"/>
</resources>

样式.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="LightTheme" parent="AppTheme">
        <item name="textColor">#000000</item>
    </style>

    <style name="DarkTheme" parent="AppTheme">
        <item name="textColor">#ffffff</item>
    </style>

</resources>

列表项.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:textColor="?attr/textColor"/>

MainActivity.java

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTheme(R.style.DarkTheme);

        setContentView(R.layout.activity_main);

  ...

标签: androidtextview

解决方案


使用 attr/textColor 内部样式

<style name="LightTheme" parent="AppTheme">
    <item name=”android:textColor”&gt;?attr/textColor</item>
</style>

然后将此样式应用于 textview。

有关详细信息,请参阅材料设计


推荐阅读