編輯:關於Android編程
Android下圖片可拖動到任意位置的效果
下面為Activity的代碼:
01
public class DraftTest extends Activity {
02
/** Called when the activity is first created. */
03
@Override
04
public void onCreate(Bundle savedInstanceState) {
05
super.onCreate(savedInstanceState);
06
setContentView(R.layout.sign);
07
DisplayMetrics dm = getResources().getDisplayMetrics();
08
final int screenWidth = dm.widthPixels;
09
final int screenHeight = dm.heightPixels - 50;
10
//拖動的按鈕
11
final Button b=(Button)findViewById(R.id.startBtn);
12
13
//添加觸摸事件
14
15
b.setOnTouchListener(new OnTouchListener(){
16
int lastX, lastY; //記錄移動的最後的位置
17
public boolean onTouch(View v, MotionEvent event) {
18
//獲取Action
19
20
int ea=event.getAction();
21
22
Log.i("TAG", "Touch:"+ea);
23
switch(ea){
24
case MotionEvent.ACTION_DOWN: //按下
25
lastX = (int) event.getRawX();
26
lastY = (int) event.getRawY();
27
break;
28
/**
29
* layout(l,t,r,b)
30
* l Left position, relative to parent
31
t Top position, relative to parent
32
r Right position, relative to parent
33
b Bottom position, relative to parent
34
* */
35
case MotionEvent.ACTION_MOVE: //移動
36
//移動中動態設置位置
37
int dx =(int)event.getRawX() - lastX;
38
int dy =(int)event.getRawY() - lastY;
39
int left = v.getLeft() + dx;
40
int top = v.getTop() + dy;
41
int right = v.getRight() + dx;
42
int bottom = v.getBottom() + dy;
43
if(left < 0){
44
left = 0;
45
right = left + v.getWidth();
46
}
47
if(right > screenWidth){
48
right = screenWidth;
49
left = right - v.getWidth();
50
}
51
if(top < 0){
52
top = 0;
53
bottom = top + v.getHeight();
54
}
55
if(bottom > screenHeight){
56
bottom = screenHeight;
57
top = bottom - v.getHeight();
58
}
59
v.layout(left, top, right, bottom);
60
Log.i("", "position:" + left +", " + top + ", " + right + ", " + bottom);
61
//將當前的位置再次設置
62
lastX = (int) event.getRawX();
63
lastY = (int) event.getRawY();
64
break;
65
case MotionEvent.ACTION_UP: //脫離
66
break;
67
}
68
return false;
69
}});
70 www.2cto.com
}
71
}
XML配置文件Sign.xml的代碼:
01
<?xml version="1.0" encoding="utf-8"?>
02
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
03
android:id="@+id/layoutRacingNeedForSpeed" android:padding="0px"
04
android:layout_width="fill_parent" android:layout_height="fill_parent">
05
<Button
06
android:id="@+id/startBtn"
07
android:text="tuodongdeanniu"
08
android:layout_centerInParent="true"
09
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
10
</RelativeLayout>
作者:Jimmy_牛牛
魅族的魅藍手機通常都是只有移動和聯通版兩種版本的,但是最近最新發布的魅藍E再次吧魅藍手機推向了一個新的高度,很多機友就開始問小編了。魅族魅藍E支持什麼SIM
如果說Android源碼中哪個地方裝飾模式應用的最明顯的話,那肯定是非ContextWrapper莫屬了,ContextWrapper是一個透明的經典的裝飾模式。本文將通
GridView用於在界面上按行、列分布顯示多個組件。GridView和ListView有共同父類:AbsListView。GridView與Lis
前言:動態加載在應用開發中有著很重要的地位,當我們項目越來越大,我們可以通過插件化來減少應用的內存,然後動態加載那些插件。還有一個方面,如果我們的應用頻繁的更新,頻繁的發