绑定后,name
和onClick
的绑定都不起作用。该按钮没有文字,点击后没有任何反应。
是因为lateinit
吗?我做到了,因为否则我必须让它可以为空,以使Kotlin高兴。因为我必须在声明它时初始化属性。我在这里缺少什么?
这是xml文件:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="authViewModel"
type="nz.salect.handset.viewmodels.AuthViewModel" />
</data>
<android.support.constraint.ConstraintLayout
...
tools:context="nz.salect.handset.view.AuthActivity">
......
<Button
...
android:onClick="@{ () -> authViewModel.lookAroundHandler() }"
android:text="@{authViewModel.name}"
... />
这是相应的观点:
class AuthActivity : AppCompatActivity() {
private lateinit var authViewModel:AuthViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth)
authViewModel = ViewModelProviders.of(this).get(AuthViewModel::class.java)
}
}
这是视图模型
class AuthViewModel:ViewModel() {
val name = "albert"
fun lookAroundHandler() {
println("I am here in view model")
}
}
已将数据绑定添加到build.gradle
:
dataBinding {
enabled = true
}
答案 0 :(得分:1)
您缺少的绑定代码
val mViewDataBinding = DataBindingUtil.setContentView(this,R.layout.activity_auth);
你不需要添加这一行
setContentView(R.layout.activity_auth)
https://developer.android.com/topic/libraries/data-binding/index.html
答案 1 :(得分:0)
试试这段代码:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_person)
(application as PeopleApplication).applicationComponent.inject(this)
val viewModelFactory: PersonViewModel.Factory = PersonViewModel.Factory(
personDataManager, this)
viewModel = ViewModelProviders.of(this, viewModelFactory).get(PersonViewModel::class.java)
binding.friendsList.adapter = PersonFriendListAdapter(viewModel)
viewModel.personData.observe(this, Observer<Person> { person ->
binding.person = person
person?.friends?.let {
(binding.friendsList.adapter as PersonFriendListAdapter).setItems(person.friends)
}
})
}
检查您的代码