拖放功能onTouch事件失败

时间:2017-11-25 21:57:16

标签: java android

您好我使用拖放选项编写了一个应用程序,我正在使用android studio 3& sdk 26 当我接触触摸事件时,我收到错误消息: java.lang.ClassCastException:android.widget.LinearLayout $ LayoutParams无法强制转换为android.widget.RelativeLayout $ LayoutParams 那是代码:

private View.OnTouchListener OnTouchListener() {

    return new View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            final int x = (int) motionEvent.getRawX();
            final int y = (int) motionEvent.getRawY();
            switch (motionEvent.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_MOVE:
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                            .getLayoutParams();
                    layoutParams.leftMargin = x - xDelta;
                    layoutParams.topMargin = y - yDelta;
                    layoutParams.rightMargin = 0;
                    layoutParams.bottomMargin = 0;
                    view.setLayoutParams(layoutParams);
                    break;
            }
            mainlayout.invalidate();
            return true;
        }
    };
}

我之前使用过该代码并且它有效,我无法理解这里的错误。

1 个答案:

答案 0 :(得分:0)

基于错误消息,该问题与拖放无关,它看起来像这部分代码:

RelativeLayout.LayoutParams lParams =(RelativeLayout.LayoutParams)                             view.getLayoutParams();

RelativeLayout.LayoutParams layoutParams =(RelativeLayout.LayoutParams)视图                             .getLayoutParams();

应更改为:

LinearLayout.LayoutParams lParams =(LinearLayout.LayoutParams)                             view.getLayoutParams();

LinearLayout.LayoutParams layoutParams =(LinearLayout.LayoutParams)视图                             .getLayoutParams();

你没有把你的xml,但我想是"查看"的父母。是LinearLayout吗?