您好,登錄后才能下訂單哦!
1)在xml里定義主題風格
<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()方法用來保存主題切換時的狀態,在下次
點擊‘切換主題’按鍵時,獲取到上次保存的狀態并設置
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){
//設置主題
setTheme(R.style.NightTheme);
}else{
setTheme(R.style.LightTheme);
}
//關聯布局
setContentView(R.layout.activity_main);
}
//設置夜間模式按鈕
public void btnNightTheme(View v){
boolean isDark = readMode();
saveMode(!isDark);
finish();
//取消Activity切換動畫
overridePendingTransition(0, 0);
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
//保存主題狀態
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;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。