摘要:今天完成了开启夜间模式功能
代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="@string/day_night_label" android:textSize="20sp" android:textColor="@color/colorDayNightChange" /> <Button android:id="@+id/day_night_change" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginLeft="5dp" android:text="日夜间模式切换" android:textSize="20sp" android:textColor="@color/colorDayNightChange"/> </LinearLayout>
package com.example.nighttheme; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; public class MainActivity extends AppCompatActivity { private Button mDayNightChange; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDayNightChange = (Button) findViewById(R.id.day_night_change); mDayNightChange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; if (mode == Configuration.UI_MODE_NIGHT_YES) { getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO); } else if (mode == Configuration.UI_MODE_NIGHT_NO) { getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES); } recreate(); } }); } }
package com.example.nighttheme; import android.app.Application; import androidx.appcompat.app.AppCompatDelegate; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); /** * 默认设置一直使用夜间模式 * * 这里AppCompatDelegate.setDefaultNightMode()方法可以接受的参数值有4个: * MODE_NIGHT_NO. Always use the day (light) theme(一直应用日间(light)主题). * MODE_NIGHT_YES. Always use the night (dark) theme(一直使用夜间(dark)主题). * MODE_NIGHT_AUTO. Changes between day/night based on the time of day(根据当前时间在day/night主题间切换). * MODE_NIGHT_FOLLOW_SYSTEM(默认选项). This setting follows the system's setting, which is essentially MODE_NIGHT_NO(跟随系统,通常为MODE_NIGHT_NO). */ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); } }
可以进行夜间模式的切换了!还没来的及整合。