Android重写View

很多时候,为了能够使程序能够更好地达到我们所需要的效果,我们需要对View进行重写,重写一个View其实是简单的,下面给出了两步就可以完成一个简单的View的重写和调用:

1.创建一个类继承View,并重写其中的onDraw方法


DemoView.class

package com.obo.mapview;

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 DemoView extends View {

    Paint paint = new Paint();
    
    public DemoView(Context context) {
        super(context);
    }
    //如果是在xml中使用该类的话,这个构造方法是必须要有的
    public DemoView(Context context, AttributeSet set)
    {
        super(context, set);
    }
    /**
     * 重新onDraw方法
     * canvas是画布,可以调用canvas的方法在界面中绘制图像
     */
    public void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        paint.setColor(Color.RED);
        //绘制圆心在(100,100)半径为50像素的红色的圆形 
        canvas.drawCircle(100, 100, 50, paint);
    }
}

2.创建一个xml文件,在其中使用自己重写的DemoView

main.xml

<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"
    tools:context=".MainActivity" >

    <com.obo.mapview.DemoView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_world" />

</RelativeLayout>

3.在Activity中显示

MainActivity.java

package com.obo.mapview;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity
{

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

}

效果显示如下,可以看到,我们在手机屏幕上绘制了一个圆形




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值