如何添加取决于应用程序主题android的TextView样式

时间:2021-08-01 21:43:29

标签: android textview android-styles android-dark-theme

在我的片段中,我有 2 个 TextView,浅色主题中有黑色(主要)和灰色(次要)颜色,深色主题中有白色(主要)和灰色(次要)颜色。我在styles.xml 和styles.xml(晚上)中为TextView 添加了新样式。但是如果我在应用程序中更改主题,文本将保持与浅色主题相同。这是它的样子:

浅色主题:

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Light" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    //
    //
    //
</style>

<style name="Theme.Light.TextView" >
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
</style>

<style name="Theme.Light.TextView.Primary">
    <item name="android:textColor">@color/black</item>
</style>

<style name="Theme.Light.TextView.Secondary">
    <item name="android:textColor">@color/grey</item>
</style>

深色主题:

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Night" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    //
    //
    //
</style>

<style name="Theme.Night.TextView" >
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
</style>

<style name="Theme.Night.TextView.Primary">
    <item name="android:textColor">@color/white</item>
</style>

<style name="Theme.Night.TextView.Secondary">
    <item name="android:textColor">@color/grey</item>
</style>

这些 TextView 的布局:

<TextView
    android:id="@+id/mainText"
    style="@style/Theme.Light.TextView.Primary"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="50dp"
    android:text="First Text"
    android:textSize="24sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/secondText"
    style="@style/Theme.Light.TextView.Secondary"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Second Text"
    android:textSize="24sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/mainText" />

light_theme_example

dark_theme_example

0 个答案:

没有答案