Android 开发必备Android应用开发那些事安卓工具相关

Android 切换主题(基础)

2019-06-17  本文已影响72人  总会颠沛流离

参考

1、Android 切换主题以及换肤的实现

截图

1、默认打开


image

2、点击【换主题色】

image

需知

主题色运用:manifest清单文件中application的属性之一,android:theme="@style/AppTheme"
在style.xml中定义不同风格的theme(对app而言的style啦)
熟悉?attr/colorPrimary等属性,在theme中定义好后,布局文件用到这些属性可以自动替换
如何点击触发后整体画面生效

代码

1、清单文件manifest中,app默认使用AppTheme(或者自定义Theme)
  <application
    ...
    android:theme="@style/AppTheme">
    ...
   </application>
2、style.xml 风格:
3、attr.xml 自定义属性(一般做自定义View的人肯定熟悉):

如果不用可忽略。这里定义后,就可在style.xml中使用这个item属性了,并可以写?attr/myBgColor 和 ?attr/myButtonHeight

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
<attr name="myBgColor" format="color" />
<attr name="myButtonHeight" format="dimension" />
</resources>
4、layout.xml 布局文件使用

这里背景使用到:android:background="?attr/myBgColor"
其中一个按钮用到:style="@style/MyBtnStyle",而这个style里面属性用到<item name="android:layout_height">?attr/myButtonHeight</item> 。 而且这个myButtonHeight定义到了2个theme里面了!!!

  <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"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="?attr/myBgColor">

<TextView
    android:id="@+id/sample_text"
    android:textSize="25sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    />

<EditText
    android:id="@+id/et_1"
    android:textSize="25sp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Edit it"/>

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="CheckBox"
    android:checked="true"/>

<Button
    android:id="@+id/btn_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="点击这里"/>

<Button
    android:id="@+id/btn_2"
    style="@style/MyBtnStyle"
    android:text="换主题色"/>

    </LinearLayout>
5、代码控制切换主题

setTheme(),必须在setContentView(),绘画画面之前
重启当前画面:recreate()
当前画面改了,但是除了栈顶的活动画面,之后新打开画面可以是新的theme,之前在栈里存活的活动画面还是不能及时换theme,这个此处不写了,太多情况了,反正可以控制的。

//切换不同的风格,必须在setContentView之前做

    if(useMyTheme){
        setTheme(R.style.MyTheme);
    }else{
        setTheme(R.style.AppTheme);
    }

    setContentView(R.layout.activity_main);


    btn_2 = findViewById(R.id.btn_2);
    btn_2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            useMyTheme = !useMyTheme;
            recreate(); //重启画面
        }
    });
上一篇 下一篇

猜你喜欢

热点阅读