實現圖片拖動,圖片拖動

來源:互聯網
上載者:User

實現圖片拖動,圖片拖動

要求:
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;@Overrideprotected 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(); //0int bottom = parentView.getBottom();   //0Toast.makeText(this, right+"---"+bottom, 1).show();*///設定touch監聽 iv_main.setOnTouchListener(this);}private int lastX;private int lastY;private int maxRight;private int maxBottom;@Overridepublic boolean onTouch(View v, MotionEvent event) {//得到事件的座標int eventX = (int) event.getRawX();int eventY = (int) event.getRawY();switch (event.getAction()) {case MotionEvent.ACTION_DOWN://得到父視圖的right/bottomif(maxRight==0) {//保證只賦一次值maxRight = parentView.getRight();maxBottom = parentView.getBottom();}//第一次記錄lastX/lastYlastX =eventX;lastY = eventY;break;case MotionEvent.ACTION_MOVE://計算事件的位移int dx = eventX-lastX;int dy = eventY-lastY;//根據事件的位移來移動imageViewint left = iv_main.getLeft()+dx;int top = iv_main.getTop()+dy;int right = iv_main.getRight()+dx;int bottom = iv_main.getBottom()+dy;//限制left  >=0if(left<0) {right += -left;left = 0;}//限制topif(top<0) {bottom += -top;top = 0;}//限制right <=maxRightif(right>maxRight) {left -= right-maxRight;right = maxRight;}//限制bottom <=maxBottomif(bottom>maxBottom) {top -= bottom-maxBottom;bottom = maxBottom;}iv_main.layout(left, top, right, bottom);//再次記錄lastX/lastYlastX = eventX;lastY = eventY;break;default:break;}return true;//所有的motionEvent都交給imageView處理}}

  

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.