我们如何在Android中使用数据绑定通过Glide将图像放入ImageView中?我看到了一些例子,但没有人帮助我。我需要设置url,但我陷入了许多教程定义或示例中。
我尝试使用xml和数据绑定设置图像,但是它不起作用
另一个问题:按钮视图中设置的图像视图图像我希望在应用启动时设置为打开。
public class LoginViewModel extends BaseObservable {
private User user;
private String successMessage = "Login was successful";
private String errorMessage = "Email or Password not valid";
private String URL_1 = "https://sftextures.com/texture/2704/0/2703/wallpaper-pattern-primitives-shades-of-grey-smaller-details-abstract-huge-texture-256x256.jpg";
private String URL_2 = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Breathe-preferences-desktop-wallpaper.svg/128px-Breathe-preferences-desktop-wallpaper.svg.png";
@Bindable
private String toastMessage = null;
@Bindable
private String url = null;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
notifyPropertyChanged(BR.url);
}
public String getToastMessage() {
return toastMessage;
}
private void setToastMessage(String toastMessage) {
this.toastMessage = toastMessage;
notifyPropertyChanged(BR.toastMessage);
}
public void setUserEmail(String email) {
user.setEmail(email);
notifyPropertyChanged(BR.userEmail);
}
@Bindable
public String getUserEmail() {
return user.getEmail();
}
@Bindable
public String getUserPassword() {
return user.getPassword();
}
public void setUserPassword(String password) {
user.setPassword(password);
notifyPropertyChanged(BR.userPassword);
}
public LoginViewModel() {
user = new User("","");
}
public void onLoginClicked() {
if (isInputDataValid()) {
setUrl(URL_1);
setToastMessage(successMessage);
}
else {
setUrl(URL_2);
setToastMessage(errorMessage);
}
}
public boolean isInputDataValid() {
return !TextUtils.isEmpty(getUserEmail()) && Patterns.EMAIL_ADDRESS.matcher(getUserEmail()).matches() && getUserPassword().length() > 5;
}
}
xml
<ImageView
android:layout_width="123dp"
android:layout_height="123dp"
android:id="@+id/image"
android:background="@color/colorAccent"
bind:imgUrl="@{viewModel.url}"/>
MainActivity
@BindingAdapter({"bind:imgUrl"})
public static void setProfilePicture(ImageView imageView, String imgUrl) {
Glide.with(imageView.getContext()).load(imgUrl).into(imageView);
}