Andrid 简易实现画面随意移动并显示坐标。
本文通过FrameLayout和LinearLayout来布局,并通过捕捉onTouchEvent事件来实现画面的随意移动,并同时显示移动后画面坐标。
1、先上布局文件:main.xml <?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: 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; } }