【转】自定义Android控件属性
Android原有的属性可能不能满足我们现在要做的事,毕竟有些人就是会天马行空的想出一些Android不会做的东西。今天就简单的写下怎样为自定义控件自定义属性,看这种描述有点晕,转过来就是控件和属性都是自定义的吧。哈~
上面是运行界面,有两个自定义的Button,主要是用来区分。
首先在res/values/
目录下新建attrs.xml文件,用来自定义属性
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyCustomWidget"> <attr name="myText" format="string"/> <attr name="isEnable" format="boolean"/> </declare-styleable> </resources>
标签declare-styleable的name值为可以通过这个值获取相关属性,这表明把这些属性赋给自定义的控件。
下面在MyCustomWidget.java的构造函数总从xml属性中读取到设置的值,利用获得的值就可以做自己的事了,代码如下:
package nbe.sense7.vinci.custom.xmlattrs; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.Button; public class CustomWedgit extends Button { public CustomWedgit(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomWidget); final int indexCount = a.getIndexCount(); for (int i = 0; i < indexCount; ++i) { int attr = a.getIndex(i); switch (attr) { case R.styleable.MyCustomWidget_myText: //获取myText属性值 String myText = a.getString(attr); //得到值后就可以按你想要的使用了,我这里是给Button设置按钮显示文字 CustomWedgit.this.setText(myText); break; case R.styleable.MyCustomWidget_isEnable: boolean isEnable = a.getBoolean(attr, false); // 这里利用布尔属性值做自己想做的 break; } } a.recycle(); } }
最后把自定义的属性加入到layout里面,main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:vinci="http://schemas.android.com/apk/res/nbe.sense7.vinci.custom.xmlattrs" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <nbe.sense7.vinci.custom.xmlattrs.CustomWedgit android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button自带text属性设置的值" /> <nbe.sense7.vinci.custom.xmlattrs.CustomWedgit android:layout_width="fill_parent" android:layout_height="wrap_content" vinci:myText="Button自定义myText属性设置的值" /> </LinearLayout>
最重要的一点是别忘了要加入上面深色的一行,xmlns:后面可以加入自定义的名字,我的是vinici,对于引号里面的值应该是xmlns:vinci="http://schemas.android.com/apk/res/你的包名"。
OK~写完手工!!
分类: Android