Reputation: 1580
Logcat Message :
java.lang.IllegalStateException: Could not find method @={() -> viewModel.onBtnClicked()(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.AppCompatButton with id 'button'
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>
File 2 : MainActivity.kt
class 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
}
}
File 3 : MainViewModel.kt
class MainViewModel : ViewModel() {
fun onBtnClicked() {
Log.d("MainViewModel", "MainViewModel")
}
}
Upvotes: 1
Views: 599
Reputation: 168
The Logcat Message is some how misleading. I was facing the same error for couple of hours checking everything else I thought it be the root cause. But for this particular error, all you have to do is to keep an eye on "{ }". This is one of the drawbacks of data binding in android. lots of the times you don't get any error on compile times, And if you do! that's not really helpful !
and another thing to consider is that '=' in
android:onClick = "@={() -> viewModel.onBtnClicked()}"
is used for a two way binding. you don't need it in this case. you can read about it here on android official docs
Upvotes: 1
Reputation: 1081
android:onClick="@{() -> viewModel.onBtnClicked()}"
Upvotes: 0