Android被逼學習例子2


接下來的這個小例子演示當手指在觸摸屏上拖動的時候,一個紅色的小球更隨手指進行移動。不過這個例子大致演示了一下自定義UI組件。

先來看看效果吧:

image

代碼大致如下:

AndroidDemoActivity.java

package Android.Demo;

import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;

public class AndroidDemoActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		LinearLayout layout = (LinearLayout) findViewById(R.id.root);
		final DrawView draw = new DrawView(this);
		draw.setMinimumHeight(300);
		draw.setMinimumWidth(300);

		draw.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent evnet) {
				// TODO Auto-generated method stub
				draw.currentX = evnet.getX();
				draw.currentY = evnet.getY();
				draw.invalidate();
				return false;
			}
		});
		layout.addView(draw);
	}
}

DrawView.java代碼如下:

package Android.Demo;

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 DrawView(Context context) {
		super(context);
	}

	@Override
	protected void onDraw(Canvas canvas) {

		super.onDraw(canvas);

		Paint p = new Paint();
		p.setColor(Color.RED);
		canvas.drawCircle(currentX, currentY, 15, p);
	}

	public float currentX = 40;
	public float currentY = 40;
}

main.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

</LinearLayout>

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com