Android studio用switch实现切换夜间模式

效果展示:

*最好在一开始就确定好自己的主题颜色,并为相关颜色命名,在设计布局时使用“@包名/颜色名字”的方式来给布局或文字设置颜色,不然如果页面很多的话颜色更改很麻烦。

步骤:

 首先打开project模式创建在res目录下创建values-night包,在这个包里建立我们夜间模式的资源。注意:日间模式下的使用颜色命名要与夜间模式的颜色命名保持一致,不然后面的切换不会进行颜色的更改。

 夜间模式:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#1A545B</color>
<color name="colorPrimaryDark">#383838</color>
<color name="colorAccent">#1A545B</color>
<color name="textColor">#DBDBDB</color>
<color name="backgroundColor">#3b3b3b</color>

</resources>

日间模式:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3BC2AE</color>
<color name="colorPrimaryDark">#F5F5F5</color>
<color name="colorAccent">#3BC2AE</color>
<color name="textColor">#FF000000</color>
<color name="backgroundColor">#FFFFFF</color>

</resources>

接着继续在res目录下建立drawable-night包,将夜间模式所需要用到的图片资源复制进来。

建立布局:

<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayout14"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/constraintLayout16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/constraintLayout15">

<TextView
android:id="@+id/textView40"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:text="夜间模式"
android:textSize="18dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="24dp"
android:scaleX="1.2"
app:layout_constraintBottom_toBottomOf="@+id/textView40"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/textView40" />

</androidx.constraintlayout.widget.ConstraintLayout> 

最后在所建立的布局文件中写入切换的Java代码就可以运行切换模式了 :

//夜间模式
Switch night = view.findViewById(R.id.switch1);
int currentMode = AppCompatDelegate.getDefaultNightMode();
if(currentMode==AppCompatDelegate.MODE_NIGHT_YES)
{
night.setChecked(true);
}
else {
night.setChecked(false);
}

night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int mode = isChecked ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO;
AppCompatDelegate.setDefaultNightMode(mode);

// 重启Activity来应用新的主题
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().finish();
getActivity().startActivity(intent);
}
});

  • 27
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值