I'm trying to use Android's Data Binding features with a custom adapter and a ListView. I'm having trouble overriding the custom adapter's getView
method:
public class ChecksAdapter extends ArrayAdapter<Check> {
public ChecksAdapter(Context context, ObservableList<Check> checks) {
super(context, R.layout.check, checks);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBinding binding = DataBindingUtil.inflate(
LayoutInflater.from(getContext()),
R.layout.check, parent, false);
binding.setCheck(this.getItem(position));
// Return what?
}
}
So my questions are:
View
element that I should be returning? Or in other words, how can I bind the object to an inflated/converted view?convertView
when using data binding?Here's the only reference of ListViews in the guide:
If you are using data binding items inside a ListView or RecyclerView adapter, you may prefer to use:
ListItemBinding binding = ListItemBinding.inflate(layoutInflater, viewGroup, false); //or ListItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false);
To create a custom binding adapter, you need to create an extension function of the view that will use the adapter. Then, you add the @BindingAdapter annotation. You have to indicate the name of the view attribute that will execute this adapter as a parameter in the annotation.
Binding adapters are responsible for making the appropriate framework calls to set values. One example is setting a property value like calling the setText() method. Another example is setting an event listener like calling the setOnClickListener() method.
To implement a binding adapter, you need to annotate the function with @BindingAdapter("attribute name here") together with View class that you want to bind to. It can be done by passing the View class (e.g. TextView ) as a function parameter or using the extension function.
implements Annotation. android.databinding.BindingAdapter. BindingAdapter is applied to methods that are used to manipulate how values with expressions are set to views.
You should do the following for smooth scrolling though..
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBinding binding;
if(convertView == null) {
binding = DataBindingUtil.inflate(
LayoutInflater.from(getContext()),
R.layout.check, parent, false);
convertView = binding.getRoot();
}
else {
binding = (CheckBinding) convertView.getTag();
}
binding.setCheck(this.getItem(position));
convertView.setTag(binding);
return convertView;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With