您的位置:首页 > 移动开发 > Android开发

Android主题应用

2015-07-01 11:12 483 查看
直接进入正文!

要设置主题首先需要定义一个自定义的属性值,

attrs.xml

<resources>
    <declare-styleable name="my_styleable">
        <attr name="colorValue" format="color" />
        <attr name="backValue" format="reference" />
    </declare-styleable>

</resources>


然后,定义对应的style。

styles.xml

<style name="Bule" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="colorValue">@color/bule_bg</item>
        <item name="backValue">@drawable/icon_bule_back</item>
    </style>
OK,现在就可以用了!

main.xml

<TextView
                android:id="@+id/tv_test"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="测试文字"
                android:textColor="?attr/colorValue"
                android:textSize="28sp" />
当然,在真正使用它的时候还需要在Activity的onCreate方法里设置:

setTheme(R.style.Bule);
//注意,一定要在setContentView之前设置主题
		setContentView(R.layout.activity_main);
设置就这么完了。看看效果吧~

现在有一个问题就是,当我们做了2款以上的主题,如果需求是获取当前主题的某一个值(比如获取当前id为:tv_test的那个textColor值),怎么办呢?

很简单,2句代码:

TypedArray ta = getTheme().obtainStyledAttributes(R.styleable.my_styleable);
//注:这个R.styleable.my_styleable_colorValue其实是自动生成的
int color = ta.getColor(R.styleable.my_styleable_colorValue, 0);
//对了,别忘了加上下面这句
ta.recycle();


OK。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: