主题定义好了,然后就是在布局文件中引用了,里面有?号的地方就是引用以上定义的label:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:background="?mainBackground"
android:orientation=“vertical” >
<TextView
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:text="?textString" />
<ImageView
android:id="@+id/ivBook"
android:layout_width=“62dip”
android:layout_height=“42dip”
android:layout_gravity=“center”
android:layout_marginTop=“0dip”
android:gravity=“center”
android:src="?btnColor" />
<Button
android:id="@+id/btnSet"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginTop=“50dp”
android:text=“改变主题” />
<Button
android:id="@+id/btnGet"
android:layout_width="wrap_content
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
"
android:layout_height=“wrap_content”
android:layout_marginTop=“50dp”
android:text=“Get Flag” />
下面就是在Activiy中定义要使用那种主题了:
public class MainActivity extends Activity {
private boolean blFlag = false;
private ImageView ivBook;
private Button btnSet;
private Button btnGet;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setTheme(R.style.MyThemeDefault);
setContentView(R.layout.main);
btnSet = (Button) findViewById(R.id.btnSet);
btnGet = (Button) findViewById(R.id.btnGet);
ivBook = (ImageView) findViewById(R.id.ivBook);
btnSet.setOnClickListener(new onClickListenerImp());
btnGet.setOnClickListener(new onClickListenerImp());
ivBook.setOnClickListener(new onClickListenerImp());
}
class onClickListenerImp implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == btnSet || v == ivBook) {
if (blFlag) {
setTheme(R.style.MyThemeDefault);
blFlag = false;
} else if (!blFlag) {
setTheme(R.style.MyThemeNight);
blFlag = true;
}
setContentView(R.layout.main);
btnSet = (Button) findViewById(R.id.btnSet);
btnGet = (Button) findViewById(R.id.btnGet);
ivBook = (ImageView) findViewById(R.id.ivBook);
btnSet.setOnClickListener(new onClickListenerImp());
btnGet.setOnClickListener(new onClickListenerImp());
ivBook.setOnClickListener(new onClickListenerImp());
} else if (v == btnGet) {
Toast.makeText(MainActivity.this, "blFlag: " + blFlag,
Toast.LENGTH_SHORT).show();
}
}
}
}
setContentView(R.layout.main);
这句后面,要重新绑定各组件及其监听器,不然只能监听一次。这是因为在setContentView后,组件不是之前那个组件了。
到此,就实现了一个简单的主题切换实现夜间模式的小Demo。
有不明白的地方,欢迎交流。
加入SharedPreference标志,可以记忆上次选用的风格,从而下次启动时不必重置。
sharedPreferences = getSharedPreferences(“UseStyle”, Context.MODE_WORLD_READABLE);
isNight = sharedPreferences.getBoolean(“isNight”, false);
if (isNight) {