android小应用,跟随手指滑动的小球

本教程旨在介绍简单的android api应用,懂得java se的看此程序不难,android的api开发与java se大体相似。
源文件:
MainActivity.java[java]
package com.example.drawcircle;

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

public class MainActivity extends Activity {

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

LinearLayout root = (LinearLayout) findViewById(R.id.root);

DrawView draw = new DrawView(this);
draw.setMinimumHeight(500);
draw.setMinimumWidth(300);

root.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;
}

}[/java]
DrawView.java[java]
package com.example.drawcircle;

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 = 30;
public float currentY = 50;
Paint p = new Paint();

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

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

public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}

/* (non-Javadoc)
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);

p.setColor(Color.GREEN);

canvas.drawCircle(currentX, currentY, 40, p);

}

/* (non-Javadoc)
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
this.currentX = event.getX();
this.currentY = event.getY();
invalidate();
return true;
// return super.onTouchEvent(event);
}

}[/java]
其中MainActivity是主activity,咋建立项目时候已经建立,至于DrawView,可以建立一个activity,也可以建立一个class并且集成android.view.View。
xml布局文件:[xml]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/root" >

</LinearLayout>[/xml]
这里使用了android的View类和xml共同控制布局文件,我们要习惯在android的xml布局文件这个优秀的习惯。

Avatar photo

About Blackford

这是个最好的时代,这是个最坏的时代,这是个充满希望的春天,这是个令人绝望的冬天,我们前面什么都有,我们前面什么都没有。梦想,让我们一次次的走远,又一次次的回头,一个关于人生的梦想还在不断奔跑,带着喜悦和疼痛,不过一切才刚刚开始,并且直到今天也远远没有结束
This entry was posted in Android开发 and tagged , , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用*标注