Android:自定义组件 随手小球

package com.example.customview;

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

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 获取布局文件中的LinearLayout布局
		LinearLayout root = (LinearLayout) findViewById(R.id.root);
		// 创建DrawView组件
		final DrawView draw = new DrawView(this);
		// 设置自定义组件的最大宽度和高度
		draw.setMinimumWidth(320);
		draw.setMinimumHeight(480);
		// 为draw组件绑定Touch事件
		draw.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				// 修改draw组件的currentX,currentY两个属性
				draw.currentX = event.getX();
				draw.currentY = event.getY();
				// 通知draw组件重绘
				draw.invalidate();
				// 返回true表明处理方法已经处理该事件
				return true;
			}
		});
		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;
	}

}

相关推荐