android学习笔记3:自定义view
在android的程序开发中我们可以根据需要开发出属于我们自己的view,来丰富我们的页面布局和功能,此时我们只需集成View这个基类,再重写其中的相关方法即可。接下来实现的这个程序,实现了一个随手指移动的小球的自定义view。/**
*
*/
package snoopy.android;
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 = 40;
public float currentY = 50;
/**
* @param context
*/
public DrawView(Context context)
{
super(context);
// TODO Auto-generated constructor stub
}
@Override
public void onDraw (Canvas canvas)
{
super.onDraw(canvas);
//创建画笔
Paint p = new Paint();
//设置画笔的颜色
p.setColor(Color.RED);
//绘制一个小圆(作为小球)
canvas.drawCircle(currentX , currentY , 15 , p);
}
}
/**
*
*/
package snoopy.android;
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 = 40;
public float currentY = 50;
/**
* @param context
*/
public DrawView(Context context)
{
super(context);
// TODO Auto-generated constructor stub
}
@Override
public void onDraw (Canvas canvas)
{
super.onDraw(canvas);
//创建画笔 www.zzzyk.com
Paint p = new Paint();
//设置画笔的颜色
p.setColor(Color.RED);
//绘制一个小圆(作为小球)
canvas.drawCircle(currentX , currentY , 15 , p);
}
}
package snoopy.android;
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 CustomView extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取布局文件中的LinearLayout容器
LinearLayout root = (LinearLayout)findViewById(R.id.root);
//创建DrawView组件
final DrawView draw = new DrawView(this);
//设置自定义组件的最大宽度、高度
draw.setMinimumWidth(300);
draw.setMinimumHeight(500);
//为draw组件绑定Touch事件
draw.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View arg0, MotionEvent event)
{
//修改draw组件的currentX、currentY两个属性
draw.currentX = event.getX();
draw.currentY = event.getY();
//通知draw组件重绘
draw.invalidate();
//返回true表明处理方法已经处理该事件
return true;
}
});
root.addView(draw);
}
}
摘自 hn307165411的专栏
补充:移动开发 , Android ,