android : drag and drop ui

來源:互聯網
上載者:User

最近在忙一些ui特效,心想這個也不是我們開發的事情阿,設計師該管的事情。最近頭痛阿,沒有辦法,還是得慢慢搞,搞開發得有點責任心,對把。這個東西呢,我在國內找了下,說的不是很清楚,大多數說的是利用WindowManager來管理要拖動的ui組件,但是我做了下,感覺麻煩,且不是我想要的效果。難道沒有利用父容器來控制ui的拖拽實現嗎?答案是有的,找了下資料,發覺效果不錯,很有借鑒意義,就分享一下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/vg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

</LinearLayout>

  代碼很簡單,主要是思路:對你想要拖拽的ui設定一個View.OntouchListener,然後在你想要實現拖拽容器(ViewGroup)裡也設定自己的View.OntouchListener.當ui被移動的時候,獲得位移資料,然後在包含ui的容器(ViewGroup)裡重新設定ui的布局屬性即可。代碼如下:

package com.android.drag_drop;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
private View selected_item = null;
private int offset_x = 0;
private int offset_y = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup vg = (ViewGroup) findViewById(R.id.vg);
vg.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
int x = (int) event.getX() - offset_x;
int y = (int) event.getY() - offset_y;

int w = getWindowManager().getDefaultDisplay().getWidth() - 100;
int h = getWindowManager().getDefaultDisplay().getHeight() - 100;
if (x > w)
x = w;
if (y > h)
y = h;
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
lp.setMargins(x, y, 0, 0);

selected_item.setLayoutParams(lp);
break;
default:
break;
}
return true;
}
});
ImageView img = (ImageView) findViewById(R.id.img);
img.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
offset_x = (int) event.getX();
offset_y = (int) event.getY();
selected_item = v;
break;
default:
break;
}

return false;
}
});
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.