【Android开发学习】自定义View

基于Android 4.2 SDK

基于Android UI组件的实现原理,开发者完全可以开发出项目定制的组件。当Android系统提供的UI组件不足以满足需求时,开发人员可以通过继承View来派生自定义组件。


布局文件如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id = "@+id/root"
    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.customview.DrawView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

自定义的组件的源代码如下(继承自View):

package com.example.customview;

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

public class DrawView extends View {
	public float currentX = 40;
	public float currentY = 50;
	
	//定义并创建画笔
	Paint p = new Paint();
	public DrawView(Context context){
		super(context);
	}
	
	public DrawView(Context context, AttributeSet set){
		super(context, set);
	}
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		p.setColor(Color.BLUE);	//设置画笔颜色
		canvas.drawCircle(currentX, currentY, 15, p);	//绘制一个小圆(作为小球)
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		//修改currentX, currentY两个属性
		currentX = event.getX();
		currentY = event.getY();
		invalidate(); //通知当前组件重绘自己
		return true;
	}

}

主文件源代码如下:
package com.example.customview;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		RelativeLayout layout = (RelativeLayout)findViewById(R.id.root);
		
		final DrawView draw = new DrawView(this);
		
		//设置自定义组件的最大宽度和高度
		draw.setMinimumWidth(300);
		draw.setMinimumHeight(500);
		layout.addView(draw);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

效果图如下:

【Android开发学习】自定义View_第1张图片


你可能感兴趣的:(【Android开发学习】自定义View)