Android 自定义View需要重写ondraw()等方法

Android  自定义View需要重写ondraw()等方法,这篇博客给大家说说自定义View的写法,需要我们继承View,然后重写一些

方法,方法多多,看你需要什么方法


首先写一个自定义的View 继承View

package com.example.engineerjspview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
/**
 * 自定义 EngineerJspView
 * @author Engineer-Jsp
 * @date 2014.10.28
 * */
import android.view.View;
public class EngineerJspView extends View{
	public float E_X = 188;  
    public float E_Y = 188;  
    Paint paint = new Paint(); 

	public EngineerJspView(Context context) {
		super(context);
	}
	public EngineerJspView(Context context, AttributeSet set){
		super(context, set); 
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		paint.setColor(Color.RED);  
        canvas.drawCircle(E_X, E_Y, 88, paint);
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		 E_X = event.getX();  
	     E_X = event.getY();  
	        invalidate();
		return false;
	}
	@Override
	protected void onAnimationStart() {
		super.onAnimationStart();
	}
	@Override
	protected void onAnimationEnd() {
		super.onAnimationEnd();
	}

}

布局文件:

<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" >

    <com.example.engineerjspview.EngineerJspView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

主活动:

package com.example.engineerjspview;
/**
 * 自定义 EngineerJspView
 * @author Engineer-Jsp
 * @date 2014.10.28 
 * */
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

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

}

效果:



自定义View看你需求而定,并不只是画图形而已,我这里只是说明下自定义View需要重写的方法~~

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。