android 自定义view属性

来源:互联网 发布:淮阴师范学院网络课程 编辑:程序博客网 时间:2024/04/28 04:10

    我们在使用android xml 布局的时候,用到的都是android 给我们定义好的view属性, 那大家有没想过自己是否可以定义view的属性呢? 这个答案肯定是可以的。

今天我就带大家来完成一下android 自定义view属性。

    自定义属性可分为3步。

     第一步:属性xml的创建。

     第二步:UI布局对属性的引用。

     第三步:java代码中对属性的获取和使用。

 一:属性xml的创建。 和创建strings.xml一样,在res-->values 目录下创建attrs.xml文件,文件内容如下:

       <?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PagedViewIcon">
        <attr name="isFavorite" format="boolean" />

        <attr name="isName" format="string" />
    </declare-styleable>
</resources>

其中  <declare-styleable name="PagedViewIcon"> 表示一个styleable, <attr name="isFavorite" format="boolean" />表示子项的名称和类型。 继续往下看,会有具体的应用。

二 :UI布局对属性的引用。 在布局中引用这个属性:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:sen="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.atest_custom_attr.MainActivity" >

    <com.example.atest_custom_attr.MyTextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        sen:isFavorite="false"/>

</RelativeLayout>

大家注意我的颜色标注,我们在使用android中默认的属性是 之所以是以android开头,就是因为图中绿色标注的原因。 所以在使用我们自定义的属性时,也需要做类似的申明,就是图中紫色区域,和android对应一样, sen是要对应的。如果你把xmlns:sen改成xmlns:ni,那么sen:isFavorite="false"就变成ni:isFavorite="false"。 其中isFavorite就是第一步中定义的子项。


三:java代码中对属性的获取和使用。

在代码中自定义一个view, 本文的例子是自定义一个TextView:

public class MyTextView extends TextView{

 public MyTextView(Context context, AttributeSet attrs) {
  super(context, attrs);
  // TODO Auto-generated constructor stub
  if(attrs != null){
   TypedArray ob = context.obtainStyledAttributes(attrs, R.styleable.PagedViewIcon);
   boolean boolean1 = ob.getBoolean(R.styleable.PagedViewIcon_isFavorite, false);
   ob.recycle();
   Log.e("AA", "---------------boolean bb = " + boolean1);
  }
 }

}

图中标注红色的区域,就是在第一步中定义的属性,注意 这里的item属性名称为declare-styleable name 加 attr name 以下划线连接而成。 即:PagedViewIcon_isFavorite(boolean 类型)

PagedViewIcon_isName(string 类型).


很简单吧, 这样就完成了自定义属性了。

0 0