切换夜间模式

本文介绍了一个简单的Android应用程序如何实现昼夜显示模式的切换。通过监听按钮点击事件,利用AppCompatDelegate调整应用主题,实现界面从白天到夜晚或者从夜晚到白天的变化,并通过SharedPreferences保存用户的偏好设置。

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btn_main);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //必须定义为  uimode
                int uimode;
                //获取当前页面的状态
                uimode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
                switch (uimode) {
                    //夜间时设置为日间
                    case Configuration.UI_MODE_NIGHT_YES:
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                        shared(false);
                        break;
                    case Configuration.UI_MODE_NIGHT_NO:
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                        shared(true);
                        break;
                }
                //重启activity
                recreate();
            }
        });
    }
    //存入状态
    private void shared(boolean flag){
        SharedPreferences sp = getSharedPreferences("Info", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putBoolean("Day",flag);
        edit.commit();

    }
}





//定义Myapp记得注册
public class Myapp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //获取状态
        SharedPreferences info = getSharedPreferences("Info", MODE_PRIVATE);
        boolean day = info.getBoolean("Day", false);
        if (day){
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        }else {

        }
    }
}

//style
<resources>

    <!-- Base application theme. -->
    //切换为  Theme.AppCompat.DayNight.DarkActionBar
    <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>

</resources>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值