Android 自定义View

       Android 的布局文件在layout下面,通常命名为*.xml。通过在XML中以XML的形式定义View,但是Android应用程序中经常需要自定义View,这就需要一个继承自Android View 的类。今天写了一个小游戏,鼠标移动的时候,View里面的红色圆球随着鼠标的移动而移动。

       UserDefineViewActivity.java

package com.example.androidexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;

public class UserDefineViewActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_draw);
		
		LinearLayout layout = (LinearLayout)findViewById(R.id.DrawLayout);
	    final DrawView drawView = new DrawView(this);
		
		layout.setMinimumHeight(500);
		layout.setMinimumWidth(300);
		
		drawView.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				// TODO Auto-generated method stub
				drawView.currentX = event.getX();
				drawView.currentY = event.getY();
				
				drawView.invalidate();
				
				return true;
			}
		});
		
		layout.addView(drawView);
	}

}

下面是继承自Android View 的类

package com.example.androidexample;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
	
	public float currentX;
	
	public float currentY;
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		Paint paint = new Paint();
		
		paint.setColor(Color.RED);
		
		canvas.drawCircle(currentX, currentY, 15, paint);
	}

	public DrawView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

}

 界面布局文件activity_draw.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DrawLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
</LinearLayout>

注意:不要忘记将UserDefineViewActivity注册到AndroidManifest.xml

运行效果

posted @ 2014-11-28 21:50  一苇渡江  阅读(287)  评论(0编辑  收藏  举报