在我的简单应用程序中,我尝试更新ImageView
网址以更改应用程序上的图像,我创建了简单的数据绑定类来实现该目的,但无法正常工作,并且没有出现任何错误
我的模型类为User
:
class User(baseContext: Context) : BaseObservable() {
val context:Context = baseContext
var username: String? = null
var password: String? = null
var profilePicUrl: String? = null
@Bindable
set(profilePicUrl) {
field = profilePicUrl
notifyPropertyChanged(BR.profilePicUrl)
}
companion object {
@JvmStatic
@BindingAdapter("android:profilePicUrl")
fun loadImage(view: ImageView, imageUrl: String) {
if (!imageUrl.isEmpty()) {
Picasso.get().load(imageUrl).into(view)
}
}
}
@Bindable
fun getProfilePicVisibility(): Int {
return if (profilePicUrl == null || profilePicUrl!!.isEmpty()) View.GONE else View.VISIBLE
}
}
LoginActivity
类:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: LoginActivityBinding = DataBindingUtil.setContentView(this, R.layout.login_activity)
binding.viewModel = ViewModelProviders.of(this, LoginViewModelFactory(this)).get(LoginViewModel::class.java)
val user = User(baseContext)
user.username = "my name"
user.password = "my family"
user.profilePicUrl = ""
binding.user = user
val handlers = ClickHandler(this)
handlers.user = user
binding.handlers = handlers
}
然后是ClickHandler
类
class ClickHandler(private val context: Context) {
var user: User? = null
fun clickOnLoginButton(view: View) {
user?.profilePicUrl = "https://www.androidhive.info/RxJava/wp-content/uploads/2018/02/1-370x247.jpg"
}
}
点击按钮后,我希望可以更新ImageView网址,并且可以使用loadImage
函数从网址中获取图片并将其附加到其中
我的简化布局:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="ir.instacheeta.application.ui.login.viewModel.LoginViewModel" />
<variable
name="user"
type="ir.instacheeta.application.ui.login.model.User" />
<variable
name="handlers"
type="ir.instacheeta.application.ui.login.viewModel.ClickHandler" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/grey_10">
...
<Button
...
android:onClick="@{handlers::clickOnLoginButton}"
... />
...
...
<com.mikhaellopez.circularimageview.CircularImageView
...
android:profilePicUrl="@{user.profilePicUrl}"
android:src="@drawable/img_wizard_1"
android:tint="@color/mdtp_white"
android:visibility="@{user.profilePicVisibility, default=gone}"
... />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
</layout>
答案 0 :(得分:0)
您已在处理程序类中声明了用户变量,该变量为null,因此您应该通过clickOnLoginButton方法将XML中的用户对象作为参数传递。
<data>
<import type="android.view.View" />
...
</data>
<Button
...
android:onClick="@{(view) -> handler.clickOnLoginButton(view,user)}"
... />
并更新您的方法
fun clickOnLoginButton(view: View,user:User)