Android: Kotlin: MVVM: ทำไม viewModel.onButtonClicked () ทำให้แอปล่ม
ข้อความ Logcat:
java.lang.IllegalStateException: ไม่พบ method @ = {() -> viewModel.onBtnClicked () (View) ในบริบทหลักหรือบรรพบุรุษสำหรับ android: onClick แอตทริบิวต์ที่กำหนดในคลาสมุมมอง androidx.appcompat.widget.AppCompatButton ด้วย id ' ปุ่ม'
File1: activity_main.xml
<data>
<variable
name="viewModel"
type="com.wingsquare.databindingdemo.MainViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick = "@={() -> viewModel.onBtnClicked()"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
ไฟล์ 2: MainActivity.kt
คลาส MainActivity: AppCompatActivity () {override fun onCreate (savedInstanceState: Bundle?) {super.onCreate (savedInstanceState)
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
// val binding = ActivityMainBinding.inflate(layoutInflater)
val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
binding.viewModel = mainViewModel
binding.lifecycleOwner = this
}
}
ไฟล์ 3: MainViewModel.kt
คลาส MainViewModel: ViewModel () {
fun onBtnClicked() {
Log.d("MainViewModel", "MainViewModel")
}
}
คำตอบ
ข้อความ Logcat เป็นวิธีที่ทำให้เข้าใจผิด ฉันพบข้อผิดพลาดเดียวกันนี้เป็นเวลาสองสามชั่วโมงในการตรวจสอบทุกสิ่งทุกอย่างที่ฉันคิดว่ามันเป็นสาเหตุ แต่สำหรับข้อผิดพลาดนี้สิ่งที่คุณต้องทำคือจับตาดู "{}" นี่เป็นข้อเสียอย่างหนึ่งของการผูกข้อมูลใน Android หลายครั้งที่คุณไม่ได้รับข้อผิดพลาดใด ๆ เกี่ยวกับเวลาคอมไพล์และถ้าคุณทำ! มันไม่มีประโยชน์จริงๆ!
และอีกสิ่งหนึ่งที่ต้องพิจารณาคือ '=' ใน
android:onClick = "@={() -> viewModel.onBtnClicked()}"
ใช้สำหรับการผูกแบบสองทาง คุณไม่จำเป็นต้องใช้ในกรณีนี้ คุณสามารถอ่านได้ที่นี่บนเอกสารทางการของ Android
android: onClick = "@ {() -> viewModel.onBtnClicked () } "
- ใส่วงเล็บต่อท้าย
- คุณอาจต้องการลบเครื่องหมายเท่ากับหลัง @