在从BaseObservable扩展的类之外实现BindingAdapter

时间:2019-04-13 04:14:30

标签: android android-databinding

在我的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);
    }
}

1 个答案:

答案 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适配器