简单举例说明android自定义view的方法

来源:互联网 发布:淘宝客qq群链接生成 编辑:程序博客网 时间:2024/05/21 10:04

自定义组件的三种方式:

(1)组合现有android默认提供的组件:继承ViewGroup或其子Layout类等布局类进行组合。

(2)调整现有Android默认提供的组件:继承View的子类具体类

(3)完全自定义组件:继承View基类,界面及事件完全由自己控制。


1、配合xml属性资源文件的方式

(1)attrs.xml文件(完成自定义组件的类文件之前,将(需要外界传入值的属性)定义成一个属性资源文件),位于工程的values下,具体写法如下:

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

(2)在自定义类里引用attrs文件里定义的属性,为自己的属性设置值------自定义view 类。如下创建一个MyView的java类

package com.example.dhasa.studydemo;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;/** * Created by dhasa on 2016/3/27. */public class MyView extends View {    //定义attrs中的属性    private int textColor;    private float textSize;    private String text;    //定义画笔,自定义获取属性并赋值之后,需要用画笔去绘制视图达到显示的目的    private Paint paint;    public MyView(Context context) {        super(context);    }    //使用定义的xml文件中的属性集合,第二个参数去接收该属性集合    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);        paint = new Paint();        //获取配置文件中的属性,并给出默认值        TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.MyView);        textColor = array.getColor(R.styleable.MyView_textColor,0xFFFFFF);        textSize = array.getDimension(R.styleable.MyView_textSize,24);        text = array.getString(R.styleable.MyView_text);    }    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    //视图的绘制事件方法(由系统调用)    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //将设计好的视图大小、颜色等“告诉”“施工方”画笔        paint.setColor(textColor);        paint.setTextSize(textSize);        //在画布上进行绘制        canvas.drawText(text,10,10,paint);    }}

(3)使用自定义组件,并设置属性。

其中xmlns定义命名空间默认为android=“”,自定义view的命名空间(名称随便定义)地址的前部分一致,apk后面为res-auto。

<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:paddingTop="20dp"    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:myDefView="http://schemas.android.com/apk/res-auto">    <com.example.dhasa.studydemo.MyView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        myDefView:textColor="#fff000"        myDefView:textSize="20sp"        myDefView:text="DHASA的csdn博客:http://blog.csdn.net/dhasa"/></LinearLayout>
在activity中将布局文件绑定即可看到自定义view的效果。


当然要想自如的写出想要的自定义控件,还要多多学习android源码view的实现原理。

0 0
原创粉丝点击