ITPub博客

首页 > IT职业 > IT图书 > 7_kotlin安卓(夜间模式)AppCompatDelegate

7_kotlin安卓(夜间模式)AppCompatDelegate

IT图书 作者:jmctian 时间:2021-09-09 10:09:05 0 删除 编辑

设置样式

图片描述

屏幕截图(97).png

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

布局文件

图片描述

屏幕截图(98).png

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

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

        <Switch
            android:id="@+id/switch1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

业务逻辑代码实现

图片描述

屏幕截图(99).png

class MainActivity : AppCompatActivity() {    companion object {
        init {AppCompatDelegate.setDefaultNightMode(
                AppCompatDelegate.MODE_NIGHT_NO)}
        }    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

switch1.setOnCheckedChangeListener { compoundButton, b ->
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)//调用recreate()使设置生效
        recreate()
    }

}
}

按照箭头操作

图片描述

屏幕截图(100).png

成功启动夜间模式

图片描述

屏幕截图(101).png



作者:莫狄
链接:https://www.jianshu.com/p/9b7c2a457d6a

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2963/viewspace-2817518/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    0
  • 访问量
    429