Android应用Theme

2014-11-23 22:59:17 · 作者: · 浏览: 9

< xml version="1.0" encoding="utf-8" >








然后再在styles文件定义两个style。


01.
07.
08.


然后就是在布局文件中使用attrs。


xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background=" attr/bgColor"
>


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"
/>



最后就是在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;
@Override
protected 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() {



@Override
public 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));
}
}


Android应用ThemeAndroid应用Theme