自定义控件的流程

Android已经提供了一系列基础控件和xml属性来帮助你创建自定义控件。

1.View的子类

View在Android是最基础的几个控件之一, 所有的控件均继承自View,你也可以直接继承View也可以继承其他的控件比如ImageView等。至少需要提供一个构造函数,其中Context和AttributeSet作为参数。 举例如下:

 class PieChart extends View{  
        public PieChart(Context context, AttributeSet attrs) {  
            super(context, attrs);  
        }  
    }  

2. 自定义属性
1) 添加自定义属性<declare-styleable>到xml文件中
2) 在xml的<declare-styleable>中,指定属性的值
3) 在view中获取xml中的值
4) 将获取的值应用到view中

举例说明:
添加 到你的程序中,习惯上一般是放在res/values/attrs.xml文件中,例如:

    <resources>  
       <declare-styleable name="PieChart">  
           <attr name="showText" format="boolean" />  
           <attr name="labelPosition" format="enum">  
               <enum name="left" value="0"/>  
               <enum name="right" value="1"/>  
           </attr>  
       </declare-styleable>  
    </resources> 
  <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
       xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">  
     <com.example.customviews.charting.PieChart  
         custom:showText="true"  
         custom:labelPosition="left" />  
    </LinearLayout>  

标准的组件的命名空间一般是http://schemas.android.com/apk/res/android
自定义的命名空间是http://schemas.android.com/apk/res/[yourPackageName],
注意:
xmlns:custom中的custom可以使用任意的字符,但要和下面的控件的定义中的字符要保持一致。
xml中的tag:com.example.customviews.charting.PieChart,需要的完整的包名

3.应用自定义的属性值
当View被创建的时候,可以通过AttributeSet读取所有的定义在xml中的属性,在构造函数中通过obtainStyledAttributes读取attrs,
该方法会返回一个TypeArray数组。通过TypeArray可以读取到已经定义在XML中的方法。下面的例子展示了读取上文中的xml属性值。

 public PieChart(Context context, AttributeSet attrs) {  
       super(context, attrs);  
       TypedArray a = context.getTheme().obtainStyledAttributes(  
            attrs,  
            R.styleable.PieChart,  
            0, 0);  

       try {  
           mShowText = a.getBoolean(R.styleable.PieChart_showText, false);  
           mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);  
       } finally {  
           a.recycle();  
       }  
    }  

需要强调的是, TypeArray使用完毕后必须要recycle,不然会发生内存泄露。

4.添加自定义的方法和事件
自定义属性只能在view初始化的时候被应用到控件中。 所以可以为每一个属性添加getter和setter,来方便操作

  public boolean isShowText() {  
       return mShowText;  
    }  

    public void setShowText(boolean showText) {  
       mShowText = showText;  
       invalidate();  
       requestLayout();  
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值