В моем простом приложении я пытаюсь обновить ImageView
URL, чтобы изменить изображение в приложении, я создаю простой класс привязки данных для реализации этого, но не работает, и я не получаю никакой ошибки
Мой класс модели как 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"
}
}
после нажатия на кнопку, я ожидаю, что URL ImageView может быть обновлен, и loadImage
функция может работать, чтобы получить изображение из URL и прикрепить к этому
мой упрощенный макет:
<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>