自定义View应该怎么定义

android自定义view组件不可避免。那么如何才能做到像官方提供的那些组件一样用xml来定义他的属性呢?废话不多说。


 一、在res/values文件下定义一个attrs.xml文件,代码如下: 
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="ToolBar"> 
        <attr name="buttonNum" format="integer"/> 
        <attr name="itemBackground" format="reference|color"/> 
    </declare-styleable> 
</resources>

二、在布局xml中如下使用该属性:
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:toolbar="http://schemas.android.com/apk/res/cn.zzm.toolbar"   // 这里注意后面cn.zzm.toolbar这路径,此路径是你定义的ToolBar类的路径
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
    <cn.zzm.toolbar.ToolBar                       //自定义的view的路径 ToolBar类
	android:id="@+id/gridview_toolbar" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:background="@drawable/control_bar" 
        android:gravity="center" 
        toolbar:buttonNum="5"                     //这个属性就是我们在res/values下的attrs.xml中定义的属性   注意格式哦
        toolbar:itemBackground="@drawable/control_bar_item_bg"/>  //同上
</RelativeLayout>


如果你要对自定义的属性要在自定义view类中进行计算等,那么在自定义组件中,可以如下获得xml中定义的值:

public ToolBar(Context context, AttributeSet attrs, int defStyle) {
	super(context, attrs, defStyle);
	roundWidth = DensityUtil.dip2px(context, 3);  
	roundHeight = DensityUtil.dip2px(context, 3);
	
	// 获取xml中定义的属性
	TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ToolBar); 
	buttonNum = a.getInt(R.styleable.ToolBar_buttonNum, 5); 
	itemBg = a.getResourceId(R.styleable.ToolBar_itemBackground, -1);
	a.recycle();
}


本文借鉴了 http://blog.csdn.net/hnjb5873/article/details/41675543


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值