Last active
March 11, 2018 06:36
-
-
Save kuluna/f625a046d707fbdd8e94d571b104cf5e to your computer and use it in GitHub Desktop.
Android DataBinding π RecyclerView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.databinding.DataBindingUtil | |
import android.databinding.ViewDataBinding | |
import android.support.annotation.LayoutRes | |
import android.support.v7.widget.RecyclerView | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
abstract class DataBindingAdapter<E, T : ViewDataBinding>(val context: Context, @LayoutRes private val layoutId: Int) : RecyclerView.Adapter<DataBindingAdapter.DataBindingViewHolder<T>>() { | |
var items = mutableListOf<E>() | |
set(value) { | |
field = value | |
notifyDataSetChanged() | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBindingViewHolder<T> { | |
val view = LayoutInflater.from(context).inflate(layoutId, parent, false) | |
return DataBindingViewHolder(view) | |
} | |
override fun getItemCount(): Int = items.size | |
override fun onBindViewHolder(holder: DataBindingViewHolder<T>, position: Int) { | |
val item = items[holder.adapterPosition] | |
bind(holder, item) | |
holder.binding.executePendingBindings() | |
} | |
fun add(item: E) { | |
items.add(item) | |
notifyDataSetChanged() | |
} | |
fun remove(item: E) { | |
items.remove(item) | |
notifyDataSetChanged() | |
} | |
abstract fun bind(holder: DataBindingViewHolder<T>, item: E) | |
class DataBindingViewHolder<out T : ViewDataBinding>(view: View) : RecyclerView.ViewHolder(view) { | |
val binding: T = DataBindingUtil.bind(view) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
val adapter = EmployeeAdapter(this) | |
binding.recyclerView.layoutManager = LinearLayoutManager(this) | |
binding.recyclerView.adapter = adapter | |
} | |
} | |
class EmployeeAdapter(context: Context) : DataBindingAdapter<EmployeeData, ListManageEmployeeBinding>(context, R.layout.list_manage_employee) { | |
override fun bind(holder: DataBindingViewHolder<ListManageEmployeeBinding>, item: EmployeeData) { | |
holder.binding.employee = item | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment