使用LiveData和DataBinding进行双向绑定
1 引入依赖包
dependencies { // ... implementation "androidx.fragment:fragment:1.0.0" implementation "androidx.lifecycle:lifecycle-viewmodel:2.0.0" implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"}
2 开启数据绑定
android { dataBinding { enabled = true }}
3 建立模型
class AuthenticationInformation(val username: String = "", val encryptedPassword: String = "")
4 建立视图模型
class AuthenticationViewModel() : ViewModel() { var authenticationInformation = MutableLiveData() var username = "Alan" set(value) { field = value authenticationInformation.postValue(AuthenticationInformation(username, encryptPassword(password))) } var password = "" set(value) { field = value authenticationInformation.postValue(AuthenticationInformation(username, encryptPassword(password))) } private fun encryptPassword(originalPassword: String): String { // ... return "******" }}
5 更新布局
6 在Activity中建立绑定关系
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) var binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.authenticationViewModel = ViewModelProviders.of(this).get(AuthenticationViewModel::class.java) binding.lifecycleOwner = this binding.getAuthenticationViewModel()?.authenticationInformation?.observe(this, object: Observer{ override fun onChanged(authenticationInformation: AuthenticationInformation) { Log.d("TEST", authenticationInformation.username) } }) }}
7 在Fragment中建立绑定关系
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { var binding = ActivityMainBinding.inflate(inflater, container, false) binding.authenticationViewModel = ViewModelProviders.of(activity) .get(AuthenticationViewModel::class.java) binding.lifecycleOwner = activity binding.getAuthenticationViewModel()? .authenticationInformation? .observe(this, object: Observer{ override fun onChanged(authenticationInformation: AuthenticationInformation) { Log.d("TEST", authenticationInformation.username) } }) return binding.root}