Android RelativeLayout动态修改子控件位置(可连续拖动的View)

学习地址来源:http://stackoverflow.com/questions/9398057/android-move-a-view-on-touch-move-action-move

另一个地方:http://blog.csdn.net/lilu_leo/article/details/7415618


做项目遇到一个需求,一个TextView需要可以在布局中任意拖动。我本来想到了自定义View,但是做了,查了半天发现难度系数有点大,于是接着换关键词为Android 可连续拖动的View,就查到了http://blog.csdn.net/lilu_leo/article/details/7415618,这篇博客,我抱着试试看的态度,用了一下发现效果挺好。完全能够满足需求,但是现实就是这么残酷,我很快发现了一个问题,点击父布局RelativeLayout其他控件,甚至,不是父布局的其他控件,这个TextView又回到了原来的位置。一看博客原来其他人也有这个问题,但是没有人说解决方案。 原来public void layout (int l, int t, int r, int b)  这个方法只是单纯的改变了子控件的位置,但是当父布局刷新是还是让它回到原来的位置,下面的这个方法可以实现让它不会回去       


public class MyActivity extends Activity implements View.OnTouchListener {

TextView _view;
ViewGroup _root;
private int _xDelta;
private int _yDelta;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    _root = (ViewGroup)findViewById(R.id.root);

    _view = new TextView(this);
    _view.setText("TextView!!!!!!!!");

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 50);
    layoutParams.leftMargin = 50;
    layoutParams.topMargin = 50;
    layoutParams.bottomMargin = -250;
    layoutParams.rightMargin = -250;
    _view.setLayoutParams(layoutParams);

    _view.setOnTouchListener(this);
    _root.addView(_view);
}

public boolean onTouch(View view, MotionEvent event) {
    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            _xDelta = X - lParams.leftMargin;
            _yDelta = Y - lParams.topMargin;
            break;
        case MotionEvent.ACTION_UP:
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            break;
        case MotionEvent.ACTION_POINTER_UP:
            break;
        case MotionEvent.ACTION_MOVE:
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
            layoutParams.leftMargin = X - _xDelta;
            layoutParams.topMargin = Y - _yDelta;
            layoutParams.rightMargin = -250;
            layoutParams.bottomMargin = -250;
            view.setLayoutParams(layoutParams);
            break;
    }
    _root.invalidate();
    return true;
}}

展开阅读全文

没有更多推荐了,返回首页