Binder
This library provides basic classes for DataBinding (BindingActivity, BindingFragment, BindingViewModel) and
also supports data change notification capabilities with no visible fields and LiveData.
UseCase
Links to examples of good use of this library can be found in the repositories listed below.
- Pokedex – 🗡️ Android Pokedex with Hilt, Motion, Coroutines, Flow, Jetpack (Room, ViewModel, LiveData) based on MVVM architecture.
- DisneyMotions – 🦁 Disney application with transformational motion based on MVVM architecture (ViewModel, Coroutines, LiveData, Room, Repository, Koin).
- MarvelHeroes – ❤️ An example of an application for Marvel heroes based on the MVVM architecture (ViewModel, Coroutines, LiveData, Room, Repository, Koin).
- TheMovies2 – 🎬 A demo project with The Movie DB based on Kotlin MVVM architecture and hardware and animation design.
Download
Berceau
Paste the following codes into your build.gradle root file (not your build.gradle module).
all projects
{repositories}
mavenCentral() }
And add the dependency code to the build.gradle file of your module.
Dependencies {Execute
“com.github.skydoves:bindables:1.0.4”}
SNAPSHOT
Snapshots of the current development version of Bindables are available to track the latest version.
Deposito’s {maven
{ url “https://oss.sonatype.org/content/repositories/snapshots/” }}
Mandatory plant information
If you are already using DataBinding in your project, you can skip this step. Add the following file to your build.gradle and make sure you are using DataBinding in your project.
plugins {
.
id Kotlin-Kapt}
Android..
.
buildFeatures {
dataBinding true}}
BindingActivity
BindingActivity is the base class for actions that want to bind a content presentation to a DataBindingUtil. It provides a binding property that extends the ViewDataBinding from abstract information. The binding property is lazily initialized, but ensures that it is initialized before super.onCreate is called in Activities. This way we don’t have to manually blow up layouts, setContentView and initialize the binding property.
classe MainActivity : BindingActivity(R.layout.activity_main) {
Override fun onCreate(saveInstanceState : Bundle ?) {
super.onCreate(opgeslagenInstanceState)
binding.vm = viewModel // we can access the “binding” property.
// Base classes provide a “bind” scope that has a receiver for the bind property. // So
we no longer need to use the `with (bind)` block.
bind {
lifeecycleOwner =
adapter [protected by email]
= PokemonAdapter()
vm = viewModel
}}}
Limiting fragment
The concept of BindingFragment is not very different from that of BindingActivity. It provides a binding property that must be initialized in onCreateView.
class HomeFragment : BindingFragment(R.layout.fragment_home) {
private VelViewModel : MainViewModel by viewModels()
Skip the fun onCreateView(
Inflatable fan: fan,
Container: viewGroup?
saveState: package ?
) : See {
super.onCreateView(inflater, container, savedInstanceState) // we need to call `super.onCreateView`.
return binding {adapter
= PosterAdapter())
vm = viewModel}
.root}}
BindingViewModel
The BindingViewModel allows the user interface to be notified of changes to the model layers.
bindingProperty
bindingProperty reports the changes in specificity that can be observed in the UI layers. The getter of the property being changed must be marked with the @get:Bindable symbol.
MainViewModel:BindingViewModel() { class
@get:Bindbar
var isLoading: boolean by bindProgtu(false)
private set // you can prevent outside access to the setter.
@get:Bindbar
var toastMessage: String? by bindProg(null) // bidirectional link.
fun fetchFromNetwork() {
isLoading = true
// … //}}
In our XML format, changes in the value of properties are automatically reported to DataBinding when we change the value.
notifyPropertyChanged .
we can configure generic property sets to notify data changes in the user interface layers by using @get:Bindable annotation and notifyPropertyChanged() in BindingViewModel.
@get:Bindbar
message var: String? = null
set(value) { field
= value//
… do something… //
notifyPropertyChanged(::message) // informs about data changes in the user interface layers. (DataBinding)}
Two-way communication
We can implement bi-directional binding properties with bindingProperty. Here is an example of a bi-directional binding with TextView and EditText.
MainViewModel:BindingViewModel() class {// This is
a linkable property because we do not set the parameter as private.
@get:Binding
var editText: String? by bindingProperty(null)}
Here is the XML format. The text is modified when viewModel.editText changes.
In your company or fragment, we can set the value of viewModel. editText every time the EditText input changes. We can implement it differently by using an inverse adapter.
binding.editText.addTextChangedListener {
vm.editText = it.toString()}
Link features
We can integrate bindable functions into BindingViewModel by using the @Bindable annotation and notifyingPropertyChanged(). The name of the @Bindable annotation method must begin with get.
MainViewModel: BindingViewModel() class {@Bindablefun getFetchedString(): String {return usecase.getFetchedData() }
fun fetchDataAndNotifyChaged() {
usecase.fetchDataFromNetowrk()
notifyPropertyChanged(::getFetchedString)}}}}
Each time we call notifyPropertyChanged(::getFetchedData), getFetchedString() is called and the UI layer receives the updated data.
android:text=”@{viewModel.fetchedData}”
Link flux
We can create a binding property for Flow with @get:Bindable and asBindingProperty. The user interface layers receive the newly collected data from Flow or StateFlow on viewModelScope. And the Flow property must be read-only (val), since its value can only be changed by observing the changes of the Flow.
MainViewModel:BindingViewModel() { class
private val stateFlow = MutableStateFlow(listOf())
@get:Bindbar.
Valley data: List after stateFlow.asBindingProperty()
@get:Bindbar
var isLoading: boolean by linkProperty(false)
private set
init {
viewModelScope.init {
stateFlow.emit(getFetchedDataFromNetwork())
// .. //}}}
Mandatory SaveStatStatIndal
We can create a binding property of SavedStateHandle in BindingViewModel with @get:Bindable and asBindingProperty(key:String). The user interface layers will receive the newly saved data from SavedStateHandle and we can set the value in SavedStateHandle if we just set the value in the property.
@HiltViewModelclass MainViewModel @Inject constructor(
private val savedStateHandle : SavedStateHandle
) : BindingViewModel() {
@get:Bindbar
var savedPage : Int? by savedStateHandle.asBindingProperty(“PAGE”)
// .. //
BindingRecyclerViewAdapter
We can create binding properties in the RecyclerViewAdapter using the BindingRecyclerViewAdapter. In the following example, the property isEmpty is visible in the XML markup. And we can report the change of the DataBinding value using the notificationPropertyChanged.
class PosterAdapter : BindingRecyclerViewAdapter() {
private trap items = mutableListOf()
@get:Bindbar.
Val isEmpty: Booleanget
() = items.isEmpty()
lustig addPosterList(lijst : Liste) {
items.clear()
items.addAll(Liste)
notifyDataSetChanged()
notifyPropertyChanged(::isEmpty)
}}
In the following example, we can ensure that the holder is not present when the adapter’s item list is empty or when data is loaded.
BindingModel
We can use the binding properties in our own classes by extending the BindingModel.
PosterUseCase class:BindingModel() {
@get:Bindbar
message var : String ? by bindingProperty(null)
private set
init {message
= getMessageFromNetwork() }}
GitHub
Related Tags:
android observable example,observablefield vs livedata,baseobservable vs viewmodel,observable android kotlin,addonpropertychangedcallback,android observablefield not found,android two-way data binding livedata,android custom view lifecycleowner,android data binding viewmodel,baseobservable,binding.lifecycleowner = viewlifecycleowner,android-databinding livedata not updating,android arsenal elegant number button,elegant android,arsenal android,plus minus button in android,androiddev digest,latest technology in android development,kotlin weekly,android development podcast,android dev podcast,styling android,Privacy settings,How Search works,android databinding onclick=@(() -> viewmodel),android databinding set viewmodel,android custom view data binding example,android data binding view model,android seekbar databinding,android data binding recyclerview livedata,android databinding lambda,android data binding imageview