引用:http://www.oschina.net/code/snippet_54100_6262
Android中自带的view种类很多,但是有时候不能满足我们的需求,下面介绍一种自定义view的方法,实现了拖动矩形到屏幕任意位置的需求。
[代码] Activity.java
03 |
import android.app.Activity; |
04 |
import android.os.Bundle; |
06 |
public class CSDNActivity extends Activity { |
07 |
/** Called when the activity is first created. */ |
09 |
public void onCreate(Bundle savedInstanceState) { |
10 |
super .onCreate(savedInstanceState); |
11 |
setContentView(R.layout.main); |
[代码] CustomView.java
03 |
import android.content.Context; |
04 |
import android.graphics.Canvas; |
05 |
import android.graphics.Color; |
06 |
import android.graphics.Paint; |
07 |
import android.graphics.Rect; |
08 |
import android.util.AttributeSet; |
09 |
import android.view.MotionEvent; |
10 |
import android.view.View; |
13 |
* 自定义的view,需要覆盖onDraw()方法绘制控件,覆盖onTouchEvent()接收触摸消息 |
15 |
public class CustomView extends View { |
17 |
private static final int WIDTH = 40 ; |
19 |
private Rect rect = new Rect( 0 , 0 , WIDTH, WIDTH); |
20 |
private int deltaX,deltaY; |
21 |
private static Paint paint = new Paint(); |
23 |
public CustomView(Context context, AttributeSet attrs) { |
24 |
super (context, attrs); |
26 |
paint.setColor(Color.RED); |
30 |
protected void onDraw(Canvas canvas) { |
31 |
canvas.drawRect(rect, paint); |
36 |
public boolean onTouchEvent (MotionEvent event) { |
37 |
int x = ( int ) event.getX(); |
38 |
int y = ( int ) event.getY(); |
39 |
switch (event.getAction()) { |
40 |
case MotionEvent.ACTION_DOWN: |
41 |
if (!rect.contains(x, y)) { |
44 |
deltaX = x - rect.left; |
45 |
deltaY = y - rect.top; |
47 |
case MotionEvent.ACTION_MOVE: |
48 |
case MotionEvent.ACTION_UP: |
49 |
Rect old = new Rect(rect); |
51 |
rect.left = x - deltaX; |
52 |
rect.top = y - deltaY; |
53 |
rect.right = rect.left + WIDTH; |
54 |
rect.bottom = rect.top + WIDTH; |
[代码] main.xml 布局文件
1 |
<? xml version = "1.0" encoding = "utf-8" ?> |
2 |
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
3 |
android:orientation = "vertical" |
4 |
android:layout_width = "fill_parent" |
5 |
android:layout_height = "fill_parent" |
7 |
< com.zhuozhuo.CustomView android:layout_width = "fill_parent" |
8 |
android:layout_height = "fill_parent" /> |