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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值