android : drag and drop ui
最近在忙一些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;
}
});
}
}
复制代码
效果图: