在我的简单应用程序中,我想更改一个图像视图URL,方法是在将默认URL设置为其中之后,单击按钮,例如在imageView中,我具有google logo图像,然后单击按钮更新为image stackoverflow logo
不幸的是,我为BindingAdapter
实施的代码仅在运行应用程序,显示google徽标图像以及更改图像url和使用notifyPropertyChanged
无效后才起作用
ImageBindingAdapter类:
object ImageBindingAdapter {
@BindingAdapter("imageUrl", "placeholder", requireAll = false)
@JvmStatic
fun loadImage(imageView: ImageView, imageUrl: String, placeholder: Drawable) {
if (imageUrl != "") {
Picasso.get().load(imageUrl)
.placeholder(R.drawable.image_not_found)
.error(R.drawable.image_not_found)
.into(imageView)
}
}
}
我的User
类具有图片网址
class User : BaseObservable() {
var username: String? = null
var password: String? = null
var profilePicUrl: String? = null
@Bindable
set(profilePicUrl) {
field = profilePicUrl
notifyPropertyChanged(BR.profilePicUrl)
}
}
然后是我的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()
user.username = "xxxx"
user.password = "xxxxxxxxxx"
user.profilePicUrl = ""
binding.user = user
val handlers = ClickHandler()
handlers.user = user
binding.handlers = handlers
}
ClickHandler
类:
class ClickHandler {
var user: User? = null
fun clickOnLoginButton(view: View) {
user?.profilePicUrl = "https://www.androidhive.info/RxJava/wp-content/uploads/2018/02/1-370x247.jpg"
}
}
提示:多次点击该ClickHandler
可以正常工作,我测试了
布局xml
<Button
...
android:onClick="@{handlers.clickOnLoginButton}"
... />
<com.mikhaellopez.circularimageview.CircularImageView
...
app:imageUrl="@{user.profilePicUrl}"
app:placeholder="@{@drawable/img_wizard_1}"
... />