很多时候,为了能够使程序能够更好地达到我们所需要的效果,我们需要对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);
}
}
效果显示如下,可以看到,我们在手机屏幕上绘制了一个圆形