仅上下移动TextView

时间:2016-06-19 11:03:00

标签: android

我只需要上下移动TextView。我有这个代码,但使用它你可以向任何方向移动TextView:

textView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                int eid = event.getAction();
                switch (eid) {
                    case MotionEvent.ACTION_MOVE:
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
                        int x = (int) event.getRawX();
                        int y = (int) event.getRawY();
                        layoutParams.leftMargin = x - 200;
                        layoutParams.topMargin = y - 250;
                        textView.setLayoutParams(layoutParams);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

有没有办法只上下移动TextView?

1 个答案:

答案 0 :(得分:1)

只需移除leftMargin分配,这将强制它仅移动垂直,因为没有任何水平向量的分配( ):

   textView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            int eid = event.getAction();
            switch (eid) {
                case MotionEvent.ACTION_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
                    int y = (int) event.getRawY();
                    layoutParams.topMargin = y - 250;
                    textView.setLayoutParams(layoutParams);
                    break;
                default:
                    break;
            }
            return true;
        }
    });