您好,登錄后才能下訂單哦!
1)在xml里定義主題風(fēng)格
<style name="NightTheme" parent="android:Theme.Holo">
<!-- API 14 theme customizations can go here. -->
</style>
<style name="LightTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- API 14 theme customizations can go here. -->
</style>
2)在代碼中使用getSharedPreferences()方法用來(lái)保存主題切換時(shí)的狀態(tài),在下次
點(diǎn)擊‘切換主題’按鍵時(shí),獲取到上次保存的狀態(tài)并設(shè)置
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean isDark = readMode();
if(isDark){
//設(shè)置主題
setTheme(R.style.NightTheme);
}else{
setTheme(R.style.LightTheme);
}
//關(guān)聯(lián)布局
setContentView(R.layout.activity_main);
}
//設(shè)置夜間模式按鈕
public void btnNightTheme(View v){
boolean isDark = readMode();
saveMode(!isDark);
finish();
//取消Activity切換動(dòng)畫
overridePendingTransition(0, 0);
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
//保存主題狀態(tài)
private void saveMode(boolean isDark) {
SharedPreferences sp = getSharedPreferences("setting", 0);
sp.edit().putBoolean("dark_mode", isDark).commit();
}
//讀取主題狀體
private boolean readMode() {
SharedPreferences sp = getSharedPreferences("setting", 0);
boolean isDark = sp.getBoolean("dark_mode", false);
return isDark;
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。