DataBinding学习,记录下来,以便查阅
1、首先添加相应的依赖和plugin
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0-rc01"
apply plugin: 'kotlin-kapt'
2、在activity或者fragment中创建ViewModel实例:
private val viewModel: UserProfileViewModel by lazy { ViewModelProvider(this.viewModelStore, this.defaultViewModelProviderFactory).get( UserProfileViewModel::class.java ) }
3、将activity或者fragment所对应的layout改成databinding布局
<?xml version="1.0" encoding="utf-8"?> <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="com.lf.jetpacktest.UserProfileViewModel" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Name: " /> <TextView android:id="@+id/user_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@{viewmodel.user.name}" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Gender: " /> <TextView android:id="@+id/user_gender" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@{viewmodel.user.gender}" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Age: " /> <TextView android:id="@+id/user_age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@{Integer.toString(viewmodel.user.age)}" /> </LinearLayout> <Button android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:onClick="@{()-> viewmodel.add()}" android:text="vote" /> <TextView android:id="@+id/count" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="@{Integer.toString(viewmodel.count)}" /> <ProgressBar android:id="@+id/progress_bar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:max="@{100}" app:hideIfZero="@{viewmodel.count}" app:progressScaled="@{viewmodel.count}" app:progressTint="@{viewmodel.count}" tools:progressBackgroundTint="@android:color/darker_gray" /> </LinearLayout> </layout>
即在最外层添加<layout></layout>布局,并将命名空间移至layout中,由代码可见,可在布局中加入相应的变量,以便于与具体的控件相绑定
4、将ViewModel与视图进行绑定
(1)在activity中
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: UserProfileLayoutBinding = DataBindingUtil.setContentView(this, R.layout.user_profile_layout) binding.viewmodel = viewModel binding.lifecycleOwner = this }
(2)在fragment中
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding: UserProfileLayoutBinding = DataBindingUtil.inflate(inflater, R.layout.user_profile_layout, container, false) binding.viewmodel = viewModel binding.lifecycleOwner = this return binding.root }
5、动态绑定数据,借助livedata
class UserProfileViewModel : ViewModel() { private val _user = MutableLiveData<User>(User("123", "male", 34)) private val _count = MutableLiveData(0) val user: LiveData<User> = _user val count: LiveData<Int> = _count fun add() { _count.value = (_count.value ?: 0) + 1 println(_count!!.value) } }
6、实现定制化绑定
@BindingAdapter("app:hideIfZero")
fun hideIfZero(view: View, number: Int) {
view.visibility = if (number == 0) View.GONE else View.VISIBLE
}
@BindingAdapter(value = ["app:progressScaled", "android:max"], requireAll = true)
fun setProgress(view: ProgressBar, count: Int, max: Int) {
view.setProgress((count * 5 ).coerceAtMost(max))
}
@BindingAdapter("app:progressTint")
fun tintProgress(view: ProgressBar, count: Int) {
val color = getAssociatedColor(count, view.context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.progressTintList = ColorStateList.valueOf(color)
}
}
private fun getAssociatedColor(count: Int, cotext: Context): Int {
return when {
count > 9 -> ContextCompat.getColor(cotext, R.color.colorAccent)
else -> ContextCompat.getColor(cotext, R.color.colorPrimary)
}
}
OK, 简单的例子完成
浙公网安备 33010602011771号