自定义View应该怎么定义

来源:互联网 发布:网络视频自己组装枪支 编辑:程序博客网 时间:2024/05/18 13:24

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