您的位置:首页 > 其它

自定义的View,实现一个跟随手指的小球

2012-05-05 22:04 489 查看
/*
* 开发自定义的View,实现一个跟随手指的小球。当用户通过手指在屏幕上拖动时,程序就监听到这个动作,并把手指动作的位置传入自定义的UI组件中,并通知该组件重绘该图。
*/

import 略

public class Ex02_2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 创建DrawView组件
final DrawView draw = new DrawView(this);
// 获取布局文件
LinearLayout root = (LinearLayout) findViewById(R.id.linearlayout);
// 设置自定义组件的最大宽度和高度
draw.setMinimumHeight(500);
draw.setMinimumWidth(300);
// 为draw组件绑定Touch事件
draw.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
// 修改组件中的currentX和currentY的值
draw.currentX = event.getX();
draw.currentY = event.getY();
// 通知draw组件重绘
draw.invalidate();
// 返回true表明处理方法已经处理了该事件
return true;
}

});
// 向布局文件中加入自定义的组件
root.addView(draw);
}
}

// 自定义一个View类,继承View
class DrawView extends View {
public float currentX = 40;
public float currentY = 50;

public DrawView(Context context) {// 构造函数
super(context);
}

// 重写View中的onDraw方法
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 创建画笔
Paint p = new Paint();
// 设置画笔颜色
p.setColor(Color.RED);
// 绘制一个小圆
canvas.drawCircle(currentX, currentY, 15, p);
}

}
/****************** XML文件代码*************************/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>


/********************************* 源程序完 ***************************/

下面看下这个程序的截图:




总结:程序中最重要的地方是重写了View中的onDraw()方法。

再利用了 canvas.drawCircle(float cx, float cy, float radius, Paint paint)方法绘制了一个圆。

android API对这个方法的参数是这样解释的:

// Draw the specified circle using the specified paint.

// If radius is <= 0, then nothing will be drawn. The circle will be filled or

// framed based on the Style in the paint.

// Parameters

// cx The x-coordinate of the center of the cirle to be drawn

// cy The y-coordinate of the center of the cirle to be drawn

// radius The radius of the cirle to be drawn

// paint The paint used to draw the circle

其实看API中我们还可学到很多方法。。。

程序中的draw.invalidate()也是必须的,它的功能是通知draw组件重图案。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: