在我的User
类中,我有一个BindingAdapter
,它的名字为loadImage
并且工作正常
class User : BaseObservable() {
var username: String? = null
var password: String? = null
var profilePicUrl: String? = null
companion object {
@BindingAdapter("android:profilePicUrl")
fun loadImage(view: ImageView, imageUrl: String) {
Picasso.get().load(imageUrl).into(view)
}
}
}
现在,由于我拥有更多类似的功能,例如,我想在其他类上使用它们:
object BindingAdapters {
@JvmStatic
@BindingAdapter("android:profilePicUrl")
fun loadImage(view: ImageView, imageUrl: String) {
Picasso.get().load(imageUrl).into(view)
}
}
我的问题是我不能在
BindingAdapters
上将此类用作Activity
或此类活动ViewModel,例如User
我的LoginActivity
班:
class LoginActivity : AppCompatActivity(), LoginResultCallbacks {
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)
}
...
}
LoginViewModel
类:
public class LoginViewModel extends ViewModel {
private User user;
private LoginResultCallbacks loginResultCallbacks;
public LoginViewModel(LoginResultCallbacks loginResultCallbacks) {
this.loginResultCallbacks = loginResultCallbacks;
this.user = new User();
}
}
LoginViewModelFactory
类
public class LoginViewModelFactory extends ViewModelProvider.NewInstanceFactory {
private LoginResultCallbacks loginResultCallbacks;
public LoginViewModelFactory(LoginResultCallbacks loginResultCallbacks) {
this.loginResultCallbacks = loginResultCallbacks;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new LoginViewModel(loginResultCallbacks);
}
}
答案 0 :(得分:0)
我认为添加绑定适配器的最佳方法是像在您的类中那样在类中添加适配器,然后唯一要做的就是模型扩展该类
class BindingAdapters : ViewModel () {
companion object {
@BindingAdapter("android:profilePicUrl")
fun loadImage(view: ImageView, imageUrl: String) {
Picasso.get().load(imageUrl).into(view)
}
}
}
public class LoginViewModel extends BindingAdapters {
private User user;
private LoginResultCallbacks loginResultCallbacks;
public LoginViewModel(LoginResultCallbacks loginResultCallbacks) {
this.loginResultCallbacks = loginResultCallbacks;
this.user = new User();
}
}
因此每个扩展BindingAdapters
的模型都可以使用profilePicUrl
适配器