linwoain的个人blog

知我者谓我心忧,不知我者谓我何求

0%

如何使用v7包快速添加夜间模式

tips:必须使用24.0.0及以后的版本。

  1. 添加v7依赖(以添加的查看版本是否为>=24.0.0):

    1
    compile 'com.android.support:appcompat-v7:24.2.0'
  2. 修改样式:

    1
    2
    3
    4
    5
    6
    <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>

    使用的样式中必须包含DayNight。

  3. 在activity中调用(必须继承自AppCompatActivity):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MainActivity extends AppCompatActivity {
static boolean isNight;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void change(View view) {
LLogUtils.i(isNight);
if (!isNight) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
LLogUtils.log();
} else {
LLogUtils.log();
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
isNight = !isNight;
recreate();
}
}
  1. 修改夜间样式

    res目录下创建values-night,在其中放入对应的资源文件

注意,调用切换方法后,必须使用recreate()方法重建view。同时Activity以前的状态会丢失。注意保存数据。