android studio中style.xml的使用

首先在布局文件中正常编写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>

以上两种写法都可以完美解决,个人推荐第一种,毕竟简单.

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值