【发布时间】:2021-02-27 22:10:40
【问题描述】:
我正在编写一个应用程序,它具有此处声明的明暗模式:
styles.xml
<style name="Noon" parent="Theme.AppCompat.NoActionBar">
<item name="upper_bg">@drawable/day_sky_top</item>
<item name="lower_bg">@drawable/day_sky</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>
</style>
<style name="Night" parent="Theme.AppCompat.NoActionBar">
<item name="upper_bg">@drawable/night_sky_top</item>
<item name="lower_bg">@drawable/night_sky</item>
<item name="android:statusBarColor">@color/colorNightDark</item>
</style>
通过关注this answer,我创建了以下文件:
/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customAttrs">
<attr name="upper_bg" format="reference" />
<attr name="lower_bg" format="reference" />
</declare-styleable>
</resources>
并像这样自定义我的 ImageView:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/top_bg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.65"
android:src="?attr/upper_bg"/>
<ImageView
android:id="@+id/bottom_bg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.35"
android:src="?attr/lower_bg"/>
</LinearLayout>
(注意这是代码的一部分,所有标签都已正确关闭。)
只要我有,一切都很好:
boolean night = true;
setTheme(night ? R.style.Night : R.style.Noon);
setContentView(R.layout.activity_main); // or whatever activity I'm in.
在我的应用的每一个 Activity 上。有没有办法一次运行此代码,以便我的主题在全局范围内更改?
【问题讨论】:
标签: java android xml layout themes