写IOS的时候很经常会自定义View 所以学习android的时候 就想自定义一个view
自定义view分为:,自绘控件、组合控件、以及继承控件
一、自绘控件
先创建一个Java类 可以继承Linearlyout FrameLayout 等 这里自绘控件继承View (必须实现几个必要的方法)
package com.example.apple.javademo.javaClass;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.example.apple.javademo.R;
//import com.example.apple.javademo.R;
/**
* Created by apple on 15/12/9.
*/
public class myview extends View
{
boolean mShowText;
int mTextPos;
String text;
Paint paint;
float mSize;
public myview(Context context, AttributeSet attrs) {
super(context, attrs);
//画笔 绘制背景色 等
paint = new Paint();
//获取属性
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.myview,
0, 0);
try
{
//获取属性 对应attrs.xml里面的属性名称 ==》对应的值
mShowText = a.getBoolean(R.styleable.myview_showText_1, false);
mTextPos = a.getInteger(R.styleable.myview_labelPosition_1, 0);
text = a.getString(R.styleable.myview_texts);
mSize = a.getFloat(R.styleable.myview_textSize1,0);
} finally {
a.recycle();
}
}
//绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制背景
paint.setColor(Color.GRAY);
canvas.drawRect(0,0,getWidth(),getHeight(),paint);
//写文字
paint.setColor(Color.RED);
paint.setTextSize(mSize);
canvas.drawText(text,10,100,paint);
}
}
创建了View之后 我们就直接可以在xml上使用ta了
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<com.example.apple.javademo.javaClass.myview
android:layout_width="match_parent"
android:layout_height="match_parent"
app:showText_1="true"
app:labelPosition_1="left"
app:textSize1="40.0"
app:texts="这是自绘控件myview,属性传入文本"
/>
</RelativeLayout>
这里会发现 有几个属性系统原本没有,
app:labelPosition_1="left"
app:textSize1="40.0"
app:texts="这是自绘控件myview,属性传入文本"
这个是自定义的属性,我们需要到系统原本的资源文件attrs.xml里创建
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myview">
<attr name="showText_1" format="boolean" />
<attr name="labelPosition_1" format="enum">
<enum name="left" value="0"/>
<enum name="right" value="1"/>
</attr>
<attr name="texts" format="string"/>
<attr name="textSize1" format="float"/>
</declare-styleable>
</resources>
之前在myview里面获取的属性就是这些value!
看一下结果: