本文通過FrameLayout和LinearLayout來佈局,並通過捕捉onTouchEvent事件來實現畫面的隨意移動,並同時顯示移動後畫面座標。
控制view移動的函數主要是scrollTo和scrollBy,兩者的差別如下:
scrollTo讓我們的layout視圖相對於屏幕的左上角進行偏移;
scrollBy是相當於我們當前的座標進行偏移,我們上面 的例子如果改成scrollBy的話,這個TextView文字會不斷地向右下角移動,多 次後我 們就不看不到這個TextView的內容了,因爲它已經進行了非Layout視圖區,而如果我們用scrollTo的話,不管點多少次按鈕,它永 遠就就 上面顯示的那個位置。
這裏我們用scrollBy更合理一些。
1、先上佈局文件:main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<?xml
version= "1.0"
encoding= "utf-8" ?>
<FrameLayout
xmlns:android= "http://schemas.android.com/apk/res/android"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent" >
<LinearLayout
android:id= "@+id/container" android:layout_width= "fill_parent" android:layout_height= "fill_parent" android:orientation= "horizontal" > <ImageView
android:src= "@drawable/icon1" android:layout_width= "wrap_content" android:layout_height= "wrap_content" /> </LinearLayout> <LinearLayout
android:id= "@+id/showXY" android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:layout_gravity= "bottom" android:orientation= "horizontal" > <TextView
android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:padding= "5px" android:text= "當前座標:" /> <TextView
android:id= "@+id/xyValue" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:padding= "5px" android:text= "0,0" />
</LinearLayout>
</FrameLayout> |
2、Activity代碼,MainActivity.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
package
org.shuxiang.test; import
android.app.Activity; import
android.os.Bundle; import
android.view.MotionEvent; import
android.view.Window; import
android.widget.LinearLayout; import
android.widget.TextView; public
class MainActivity extends Activity { private
LinearLayout container; private
int currentX; private
int currentY; private
TextView xyValue; @Override public
void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); container
= (LinearLayout) findViewById(R.id.container); xyValue
= (TextView) findViewById(R.id.xyValue); } @Override
public
boolean onTouchEvent(MotionEvent event) {
switch
(event.getAction()) {
case
MotionEvent.ACTION_DOWN: {
currentX
= (int) event.getRawX(); currentY
= (int) event.getRawY(); break ;
}
case
MotionEvent.ACTION_MOVE: {
int
x2 = (int) event.getRawX(); int
y2 = (int) event.getRawY(); container.scrollBy(currentX
- x2 , currentY - y2); currentX
= x2; currentY
= y2; xyValue.setText(x2
+ ","
+ y2); break ;
}
case
MotionEvent.ACTION_UP: {
break ;
}
}
return
true ;
}
}
原文地址:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2013/0111/800.html
|