自定义一般分三种情况
1. 自定义布局
2. 自定义控件
3.直接继承View
下面来着eoe例子,实现自定义控件
1. 自定义属性
res/values/attrs.xml 自定义属性
<?xml version="1.0" encoding="utf-8"?> <resources><declare-styleable name="progress"><attr name="text" format="string" /><attr name="textSize" format="dimension" /></declare-styleable> </resources>
2. 自定义控件,实现带有 AttributeSet的构造方法
package com.test.uidemo;import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import android.widget.TextView;import com.test.uidemo.R;/*** 参考eoe书籍* 自定义控件* 实现用一个边框把文字包裹.*/ public class MyTextView extends TextView {public MyTextView(Context context) {super(context);}public MyTextView(Context context, AttributeSet attrs) {super(context, attrs);TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.progress);setText(attr.getString(R.styleable.progress_text));setTextSize(attr.getDimension(R.styleable.progress_textSize, 16));Log.i("Text", attr.getString(R.styleable.progress_text));}protected void onDraw(Canvas canvas){super.onDraw(canvas);Paint paint = new Paint();paint.setColor(android.graphics.Color.RED);canvas.drawLine(0,0,this.getWidth()-1,0,paint);canvas.drawLine(0,0,0,this.getHeight()-1,paint);canvas.drawLine(this.getWidth()-1,0,this.getWidth()-1,this.getHeight()-1,paint);canvas.drawLine(0,this.getHeight()-1,this.getWidth()-1,this.getHeight()-1,paint);}}
3. 使用自定义控件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:progress="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"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.test.uidemo.MainActivity"><com.test.uidemo.MyTextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"progress:text="自定义"progress:textSize="30dp"android:layout_centerVertical="true"android:layout_alignParentRight="true"android:layout_alignParentEnd="true"></com.test.uidemo.MyTextView></RelativeLayout>