您好,登錄后才能下訂單哦!
要求:
1.通過手指移動來拖動圖片
2.控制圖片不能超出屏幕顯示區域
技術點:
1.MotionEvent處理
2.對View進行動態定位(layout)
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/iv_main" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/test"/> </RelativeLayout>
MainActivity:
public class MainActivity extends Activity implements OnTouchListener { private ImageView iv_main; private RelativeLayout parentView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_main = (ImageView) findViewById(R.id.iv_main); parentView = (RelativeLayout) iv_main.getParent(); /* int right = parentView.getRight(); //0 int bottom = parentView.getBottom(); //0 Toast.makeText(this, right+"---"+bottom, 1).show(); */ //設置touch監聽 iv_main.setOnTouchListener(this); } private int lastX; private int lastY; private int maxRight; private int maxBottom; @Override public boolean onTouch(View v, MotionEvent event) { //得到事件的坐標 int eventX = (int) event.getRawX(); int eventY = (int) event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //得到父視圖的right/bottom if(maxRight==0) {//保證只賦一次值 maxRight = parentView.getRight(); maxBottom = parentView.getBottom(); } //第一次記錄lastX/lastY lastX =eventX; lastY = eventY; break; case MotionEvent.ACTION_MOVE: //計算事件的偏移 int dx = eventX-lastX; int dy = eventY-lastY; //根據事件的偏移來移動imageView int left = iv_main.getLeft()+dx; int top = iv_main.getTop()+dy; int right = iv_main.getRight()+dx; int bottom = iv_main.getBottom()+dy; //限制left >=0 if(left<0) { right += -left; left = 0; } //限制top if(top<0) { bottom += -top; top = 0; } //限制right <=maxRight if(right>maxRight) { left -= right-maxRight; right = maxRight; } //限制bottom <=maxBottom if(bottom>maxBottom) { top -= bottom-maxBottom; bottom = maxBottom; } iv_main.layout(left, top, right, bottom); //再次記錄lastX/lastY lastX = eventX; lastY = eventY; break; default: break; } return true;//所有的motionEvent都交給imageView處理 } }
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持億速云!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。