檬檬之魂吧 关注:8贴子:870
  • 2回复贴,共1

【檬檬--记录】自定义控件属性

取消只看楼主收藏回复

以Button为例说明,自定义Button按钮上的字体大小和字体颜色


1楼2015-01-25 19:19回复
    1、在values文件夹下面增加attrs.xml
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <declare-styleable name="mybutton">
    <attr name="textSize" format="dimension" />
    <attr name="textColor" format="color" />
    </declare-styleable>
    </resources>
    属性值集合,集合变量名为mybutton,属性值有textSize,textColor
    类似于array数组,数组名为mybutton,数组值为textSize,textColor
    format :reference、string、color、dimension、boolean、integer、float、fraction、enum、flag


    3楼2015-01-25 19:28
    回复
      2、自定义TextButton.java文件,继承Button控件
      public class TextButton extends Button{
      public TextButton(Context context, AttributeSet attrs) {
      super(context, attrs);
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.mybutton);
      this.setTextSize(a.getDimension(R.styleable.mybutton_textSize,50));
      this.setTextColor(a.getColor(R.styleable.mybutton_textColor,0x7f04008d));
      a.recycle();
      }
      }
      ①TypedArray实例是个属性的容器,context.obtainStyledAttributes()方法返回得到。AttributeSet是节点的属性集合,在本例中是<com.example.test.TextButton节点中的属性集合。
      ②a.getDimension(R.styleable.mybutton_textSize,50)获取自定义的TextSize大小为50sp
      a.getColor(R.styleable.mybutton_textColor,0x7f04008d)获取自定义的TextColor为蓝色,0x7f04008d是R文件里的int值
      ③a.recycle();必不可少,Give back a previously retrieved StyledAttributes, for later re-use.


      5楼2015-01-25 19:37
      回复