首先在布局文件中正常编写View的属性,然后点击右键打开菜单,依次选择Refactor -> Extract -> Style,如图所示:
在弹出的提取style对话框中,选择所需要的属性,如图所示:
为style命名,点击ok,然后就可以在style.xml文件中看到这个style了.
下面讲解如何在style中使用自定义属性.
在layout布局中使用自定义属性非常简单,我们只需要在xml根节点的后面加上我们自定义控件的命名空间.然后就可以在自定义控件节点里使用我们的自定义属性了。
xmlns:Android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/apk/res/packagename
自定义属性在layout布局xml中可以使用正常,但是却无法在style中定义,我在编写style的时候,以为style.xml也应该是这种使用方式,于是就在根节点添加了自定义控件的命名空间,然后就在style中开始使用自定义属性,如下:
<resources
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:test="http://schemas.android.com/res/com.zhufuing" >
<style name="JellyToggleButtonStyle">
<item name="jtbLeftTextColor">@android:color/black</item>
<item name="jtbLeftTextSize">16sp</item>
<item name="jtbLeftThumbColor">#f00</item>
</style>
</resources>
这种方式编译报错,程序找不到这些属性:
error: Error: No resource found …
其实在style中使用自定义属性直接写属性名就可以:
<style name="JellyToggleButtonStyle">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="jtbJelly">itself</item>
<item name="jtbTextMarginBottom">2dp</item>
</style>
还有一种解决方法是在属性前面加上项目的包名亲测可以
ps:是包名,不带自定义控件的名字
<style name="JellyToggleButtonStyle">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="com.gz.gzcar:jtbJelly">itself</item>
<item name="com.gz.gzcar:jtbLeftBackgroundColor">@android:color/white</item>
</style>
以上两种写法都可以完美解决,个人推荐第一种,毕竟简单.