android 之自定义View

今天闲着无聊,开个博客玩玩,也算是一个学习的过程吧。废话不不多说了。

目的:

自定义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.好啦,吃饭去了。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值