如何将onTouch中的视图移动限制为Android中的父视图?

时间:2016-08-11 16:43:57

标签: java android android-layout listview android-recyclerview

这似乎很容易说明,但似乎没有直接的实施。我想限制imageview移动到它的直接父级。我找不到与此相关的例子。有人可以帮我举个例子吗? 我实际上想要实现一个动作,其中中间的叶子移动,顶部的叶子应该移动到底部,底部的叶子应该移动到中间,中间的叶子应该移动到顶部位置。这与中间叶片的高度相结合。请参考下图。 我试图通过在视图的onTouch中使用父视图的rect来实现这一点,但这似乎不起作用。试图实现这个listview和recyclerview,但这似乎为简单的要求增加了很多复杂性。

enter image description here

这是我的代码

public class Main6Activity extends AppCompatActivity {

ImageView imageView;
private int _xDelta;
private int _yDelta;
View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main6);
    imageView = (ImageView)findViewById(R.id.img1);


     view = findViewById(R.id.imglayout);
   final Rect rect = new Rect(view.getLeft(),view.getTop(),view.getRight(),view.getBottom());
    imageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();
            if(event.getAction() ==  MotionEvent.ACTION_DOWN){
                LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
                _xDelta = X - lParams.leftMargin;
                _yDelta = Y - lParams.topMargin;
            }

            if (event.getAction() == MotionEvent.ACTION_MOVE){
                if(isViewContains(X,Y)){
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
                    layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = -250;
                    layoutParams.bottomMargin = -250;
                    imageView.setLayoutParams(layoutParams);
                }

            }
            return true;
        }
    });


}
private boolean isViewContains(int rx,int ry) {
    int[] l = new int[2];
    view.getLocationOnScreen(l);
    Rect rect1 = new Rect(l[0], l[1], l[0] + view.getWidth(), l[1] + imageView.getHeight());
    return rect1.contains(rx, ry);
 }
}

0 个答案:

没有答案