androidx.constraintlayout.widget.ConstraintLayout$LayoutParams 无法转换为 android.widget.RelativeLayout$LayoutParams

androidx.constraintlayout.widget.ConstraintLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

我是 Android Studio 的新手,我只想拖动一个 TextView。但是,当我尝试获取 RelativeLayout 的 LayoutParams 时,我得到了 class 我不使用 (ContraintLayout) 的 ClassCastException。

    import androidx.appcompat.app.AppCompatActivity;

    import android.os.Bundle;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.RelativeLayout;
    import android.widget.TextView;

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView=findViewById(R.id.textView);
        textView.setOnTouchListener(onTouchListener());
    }

    private View.OnTouchListener onTouchListener(){
        return new View.OnTouchListener(){
            @Override
            public boolean onTouch(View view, MotionEvent event){
                final int x= (int)event.getRawX();
                final int y= (int)event.getRawY();
                RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams)view.getLayoutParams();//<--ERROR
                return true;
            }
        };
    }
}

这是错误信息

E/InputEventReceiver: Exception dispatching input event.
E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
E/MessageQueue-JNI: java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
    at com.example.test.MainActivity.onTouch(MainActivity.java:28)

我想在您的 activity_main.xml 中您有带有 TextView 的 ConstraintLayout,因此您应该在 java 代码中使用 ConstraintLayout.LayoutParams。或者您可以在 activity_main.xml 中将 ConstraintLayout 更改为 RelativeLayout。这取决于您要实现的目标