android 自定义控件的style

    今天看了一下checkboxPreference的实现,对如何引用到checkbox layout的一头雾水,于是好好补习了下style and theme ,也自己实现了一个自定义的preference 。

自定义Radiopreference的两种方法

1. 直接使用 widgetlayout属性指定 layout文件,这个是android 提供的接口 ,这种方式需要在每个radioPreference 中都要引用该layout,不详细记录。

2. 模仿checkboxPreference方式 定义控件。
    步骤:
          1. 在attrs.xml 中定义 该 控件对应的style名称,这个名称应该与theme中定义的相同,在checkbox的例子中就是 R.attr.checkBoxPreferenceStyle  , 这里我们命名为 radioPreferenceStyle

<? xml  version = "1.0"  encoding = "utf-8" ?>
<resources>

     < declare-styleable  name = "RadioPreference" >
         < attr  name = "radioPreferenceStyle"  format = "reference"  />
         < attr  name = "radioPreference_summaryOn"  format = "reference"  />
         < attr  name = "radioPreference_summaryoff"  format = "reference"  />
     </ declare-styleable  >

</ resources >

2. 在 values/themes.xml中定义theme ,theme中增加 item 。该item的名字与attrs中的对应

<?xml version="1.0" encoding= "utf-8"?>
<resources>
     <style name="AppTheme" parent="android:Theme.Light" >
        <item name="radioPreferenceStyle" >@style/preference_radioButton</ item>
    </style >
</resources>

3. 在values/styles.xml中定义具体的radioPreference 属性. 其实也是使用的widgetlayout 属性.

<resources xmlns:android="http://schemas.android.com/apk/res/android" >
    <style name="preference_radioButton">
        <item name="android:widgetLayout" >@layout/preference_radionbutton</ item>
    </style >
</resources>

4. 在radioPreference中加载

 public RadioPreference(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
             
              TypedArray a = context.obtainStyledAttributes(attrs,
                   R.styleable.RadioPreference, defStyle, 0);
        
              a.recycle();
          }
          public RadioPreference(Context context, AttributeSet attrs) {
//radioPreferenceStyle 定义了radiopreference的样式引用。
              this(context, attrs, R.attr.radioPreferenceStyle);
          }
          public RadioPreference(Context context) {
              this(context, null);
          }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值