android 使用Theme + attr换肤

来源:互联网 发布:数据分析处理是什么 编辑:程序博客网 时间:2024/06/06 03:51

项目有支持夜间模式的需求,开始从theme一点点摸索。据了解。很多人采用的方式是更换主题后发送通知,所有界面在接受到通知后,重新set一遍控件。这样的好处是不需要重启界面,但是代码写起来比较繁琐,且代码量很大。

首先从Theme + attr结合的方式开始,比如说在attr.xml里可以定义如下属性:

<attr name="btnColor" format="color" />    <attr name="mainBackground" format="color" />    <attr name="mainTextColor" format="reference|color" />    <attr name="textString" format="string" />     <attr name="textStyle" format="reference"></attr>    <declare-styleable name="EditTextExt">        <attr name="TextColor" format="reference|string"></attr>    </declare-styleable><span style="font-family: Arial, Helvetica, sans-serif;"></span>

然后在styles.xml里定义主题:

<!-- 默认 -->    <style name="MyThemeDefault" parent="@android:style/Theme">        <item name="btnColor">#00ff00</item>        <item name="mainBackground">#ffffff</item>        <item name="mainTextColor">#367895</item>        <item name="textString">默认主题</item>        <item name="textStyle">@style/textStyle.TMyTextStyle</item>    </style>    <!-- 夜间 -->    <style name="MyThemeNight" parent="@android:style/Theme">        <item name="btnColor">#0000ff</item>        <item name="mainBackground">#000000</item>        <item name="mainTextColor">#555555</item>        <item name="textString">夜间主题</item>        <item name="textStyle">@style/textStyleNight.TMyTextStyle</item>    </style>
我们可以在theme里定义好某个属性的颜色,然后在具体的style中使用: 

    <style name="TextColorSection">        <item name="android:textColor">?attr/mainTextColor</item>    </style>
设置主题有两种途径,一种是在activity里设置,一种是在fragment里设置。

在Activity中设置的方法如下,在onCreate函数里根据当前主题设置:

setTheme(R.style.MyThemeNight);
在inflate布局时要注意,使用当前activity的Context加载布局,如mContext.getLayoutInflater.inflate.不然在加载布局时会找不到设置的属性值而崩溃。

在fragment里设置主题时,在onCreateView里进行如下设置:

Context ctxWithTheme;    ctxWithTheme = new ContextThemeWrapper(getActivity().getApplicationContext(), R.style.MyThemeNight);     mInflater = inflater.cloneInContext(ctxWithTheme); 
在加载布局时使用创建的mInflater进行加载。

个人理解,这两种方法本质上都是将theme的内容添加到当前的上下文信息context中进行加载。


在代码中可以使用如下方法,使用attr属性设置颜色。。再也不用if else啦。。

<pre name="code" class="java">TypedValue typedValue = new TypedValue();         MainActivity.getInstance().getTheme().resolveAttribute(R.style.TextColorItemTitle, typedValue, true);         int[] attribute = new int[] { R.attr.text_cl_title };         TypedArray array = MainActivity.getInstance().obtainStyledAttributes(typedValue.resourceId, attribute);         int textColor = array.getColor(0, R.color.kw_commen_color_white);         tabView.setTextColor(textColor);         array.recycle();








0 0
原创粉丝点击