Android之自定义view及自定义属性

前一段时间面试碰到一面试题,说难也不难,说简单但也没接触过,可能是自己基础太薄弱了,这一问题面试官问到:自定义view很简单,但自定义view的属性如何添加呢?当时我没回答出来,一脸蒙蔽!后来回来上网查了下自定义view的自定义属性,才知道原来这么简单。

我们知道自定义view,只要继承view,然后复写onMeasure、onLayout、onDraw方法即可实现,但是如何给自定义好的view添加自己的属性呢?
下面我们用个简单的demo例子来讲解一下:

一、自定义view代码

package cn.jhsys.defineviewdemo;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public void init(AttributeSet attrs){  

        TypedArray t = getContext().obtainStyledAttributes(attrs,R.styleable.MyElement);  

        String textValue = t.getString(R.styleable.MyElement_textValue);  
        float textSize = t.getDimension(R.styleable.MyElement_textSize, 36);  
        int textColor = t.getColor(R.styleable.MyElement_textColor, 0xff000000);  

        System.out.println("textValue=" + textValue + ",textSize=" + textSize
                + ",textColor=" + textColor);
    }

}

二、布局文件

<LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
 xmlns:my="http://schemas.android.com/apk/res/cn.jhsys.defineviewdemo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <cn.jhsys.defineviewdemo.MyView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        my:textValue="你好1"
        my:textColor="#ff00"/>
    <cn.jhsys.defineviewdemo.MyView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        my:textValue="你好2"
        my:textColor="#22ff"/>

</LinearLayout>

这里有两个地方需注意:1、布局文件的新增一个命名空间,xmlns:my=”http://schemas.android.com/apk/res/cn.jhsys.defineviewdemo” ,名称my可以任意更改,后面是该应用的包名;2、引用自定义view时,需连带包名一起,

三、attrs.xml文件

需在values下新建一个attrs.xml文件,内容你可以自定义啦

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyElement">  
        <attr name="textColor" format="color" />  
        <attr name="textSize" format="dimension" />  
        <attr name="textValue" format="string" />  
    </declare-styleable>
</resources>

关于自定义view如何添加自定义属性,就简单的说到这了。

demo下载地址:http://download.csdn.net/detail/wufeiqing/9505682

猜你喜欢

转载自blog.csdn.net/wufeiqing/article/details/51275864