当前位置: 代码迷 >> Android >> Android正题应用
  详细解决方案

Android正题应用

热度:84   发布时间:2016-04-28 00:14:02.0
Android主题应用

直接进入正文!

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

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。



版权声明:本文为博主原创文章,未经博主允许不得转载。

  相关解决方案