1

I'm new to Android Studio and I just want to drag a TextView around. However, when I try to get the LayoutParams for the RelativeLayout, I get a ClassCastException for a class I don't use (ContraintLayout).

    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;
            }
        };
    }
}

here is the error message

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$1.onTouch(MainActivity.java:28)
2
  • What is your activity_main layout? Commented Sep 17, 2019 at 18:31
  • Romadro was correct in saying I have a ContraintLayout in my activity_main.XML. I didn't realize that contraintLayout was the default, and I just needed to change it to relativeLayout. Commented Sep 18, 2019 at 22:20

1 Answer 1

2

I suppose in your activity_main.xml you have ConstraintLayout with TextView inside it, so your should use ConstraintLayout.LayoutParams in your java-code instead. Or you may change ConstraintLayout to RelativeLayout in your activity_main.xml. It depends on what you are trying to implement

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.