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

  • 内容
  • 评论
  • 相关

本教程旨在介绍简单的android api应用,懂得java se的看此程序不难,android的api开发与java se大体相似。
源文件:
MainActivity.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;
	}

}

DrawView.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);
	}

}

其中MainActivity是主activity,咋建立项目时候已经建立,至于DrawView,可以建立一个activity,也可以建立一个class并且集成android.view.View。
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>

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

评论

0条评论

发表评论

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