今天闲着无聊,开个博客玩玩,也算是一个学习的过程吧。废话不不多说了。
目的:
自定义View
1.既然是自定义view,那就坑定是继承View 然后重写里面的一些方法了。
2OK let's go
3, 最重要的当然是代码了,来了!
package com.example.myview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyView extends View{
private Context context;
private Paint paint;
//自己调用的
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
//这个一定要写,你放在XML里面要调用的,一定要写啊
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
//最重要方法来了
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//在这里你就可以为所欲为
//既然这里有canvas了,当然paint 少不了啊
paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(100, 100, 30, paint);
paint.setColor(Color.GREEN);
canvas.drawText("自己定义的View", 100,100, paint);
}
}
4,然后就是在布局里面引用了
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<com.example.myview.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
5,引用就是对自己的类的地址的应用
当然啦,,没图说个JB
6.好啦,吃饭去了。