Android 切换日夜间模式

本文介绍了一个简单的Android应用程序如何实现主题切换功能。通过在attrs.xml中定义颜色属性,在styles.xml中设置不同主题的颜色值,并利用SharedPreferences保存当前主题状态,最终实现了用户界面从日间到夜间模式的动态变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在attrs.xml文件中配置属性

  <attr name="mainBackground" format="color"/>

在layout.xml文件中使用

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="?mainBackground"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnSet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="夜间模式" />

</LinearLayout>

在styles.xml文件中

 <style name="DayTheme" parent="@android:style/Theme">
        <item name="mainBackground">#ffffff</item>
    </style>

    <!-- 夜间模式 -->

    <style name="NightTheme" parent="@android:style/Theme">
        <item name="mainBackground">#000000</item>
    </style>

在MainActivity中

public class MainActivity extends Activity implements OnClickListener {

    private Button btnSet;

    private boolean isnightMode = false;// 设置一个标记,表示是否为夜间模式

    private String text;

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

        showTheme();// 显示主题操作

        setContentView(R.layout.activity_main);// 重新加在布局

        initView();// 初始化控件

        showText();

        initSetOnClickListener();// 初始化点击事件

    }

    private void showTheme() {
        isnightMode = SharedPreferencesUtils.getBoolean(this, "night_mode",
                "night_mode");

        if (!isnightMode) {
            setTheme(R.style.DayTheme);

        } else {
            setTheme(R.style.NightTheme);

        }
    }

    private void showText() {
        if (!isnightMode) {
            text = "夜间模式";
        } else {
            text = "日间模式";
        }

        btnSet.setText(text);

    }

    private void initView() {
        btnSet = (Button) findViewById(R.id.btnSet);
    }

    private void initSetOnClickListener() {
        btnSet.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        if (!isnightMode) {// 表示日间模式

            setTheme(R.style.NightTheme);

        } else {
            // 切换为日渐模式
            setTheme(R.style.DayTheme);

        }

        isnightMode = !isnightMode;// 改变标记
        // 保存
        SharedPreferencesUtils.saveBoolean(this, "night_mode", "night_mode",
                isnightMode);

        setContentView(R.layout.activity_main);// 重新加在布局

        initView();

        showText();

        initSetOnClickListener();

    }

}

说明:SharedPreferencesUtils是自己写好的工具类

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值