標籤:android theme attrs styles
android切換Theme主流三種方式來切換Theme,第一種是通過內建的style來切換,一般用於夜間模式/日間模式切換。第二種是通過apk來實現外掛程式化,第三種是通過下載zip進行解壓到到相應的app檔案下,應用講需要檔案讀取到記憶體中。這篇是介紹第一種android切換Theme的方法。
首先當然是在values下面建立attrs檔案,然後定義了一些attr。
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="main"> <attr name="bgColor" format="color"></attr> <attr name="buttonBgColor" format="color"></attr> <attr name="buttonTextColor" format="color"></attr> <attr name="textSize" format="dimension"></attr> </declare-styleable> </resources>
然後再在styles檔案定義兩個style。
<style name="dayTheme"> <item name="bgColor">#ffffff</item> <item name="buttonBgColor">#80000000</item> <item name="buttonTextColor">#80ffffff</item> <item name="textSize">14sp</item> </style> <style name="nightTheme"> <item name="bgColor">#cc000000</item> <item name="buttonBgColor">#80ffffff</item> <item name="buttonTextColor">#80000000</item> <item name="textSize">14sp</item> </style>
然後就是在布局檔案中使用attrs。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?attr/bgColor" > <Button android:id="@+id/swtichThemeBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="?attr/textSize" android:text="按下按鈕切換夜間模式" android:layout_margin="10dip" android:background="?attr/buttonBgColor" android:textColor="?attr/buttonTextColor" /></LinearLayout>
最後就是在mainActivity設定theme並動態切換theme。
import android.os.Bundle;import android.preference.PreferenceManager;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button mSwtichThemeBtn;private boolean isNight;private SharedPreferences sp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);sp = PreferenceManager.getDefaultSharedPreferences(this);setTheme((isNight = sp.getBoolean("isNight", false)) ? R.style.nightTheme : R.style.dayTheme);setContentView(R.layout.activity_main);mSwtichThemeBtn = (Button) this.findViewById(R.id.swtichThemeBtn);mSwtichThemeBtn.setText(isNight?"切換日間模式":"切換夜間模式");mSwtichThemeBtn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Editor edit = sp.edit();edit.putBoolean("isNight", !isNight);edit.commit();recreateForTheme();}});}@SuppressLint("NewApi")public void recreateForTheme(){if(android.os.Build.VERSION.SDK_INT >= 11){this.recreate();}else{this.finish();startActivity(new Intent(MainActivity.this,MainActivity.class));}}