我是 Android Studio 的新手,我只想拖動(dòng) TextView。但是,當(dāng)我嘗試獲取RelativeLayout 的LayoutParams 時(shí),我得到了一個(gè)我不使用的類(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; } }; }}這是錯(cuò)誤消息E/InputEventReceiver: Exception dispatching input event.E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallbackE/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)
1 回答

千萬里不及你
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
我想在你的activity_main.xml中你有ConstraintLayout,里面有TextView,所以你應(yīng)該在你的java代碼中使用ConstraintLayout.LayoutParams?;蛘吣梢栽赼ctivity_main.xml 中將ConstraintLayout 更改為RelativeLayout。這取決于您想要實(shí)現(xiàn)的目標(biāo)
添加回答
舉報(bào)
0/150
提交
取消