我正在尝试将Android's Data Binding features与自定义适配器和ListView一起使用。我无法覆盖自定义适配器的getView
方法:
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?
}
}
所以我的问题是:
View
元素?或者换句话说,如何将对象绑定到膨胀/转换的视图?convertView
?以下是本指南中ListViews的唯一参考:
如果您在ListView或RecyclerView适配器中使用数据绑定项,您可能更喜欢使用:
ListItemBinding binding = ListItemBinding.inflate(layoutInflater, viewGroup, false); //or ListItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false);
答案 0 :(得分:21)
您应该执行以下操作以平滑滚动..
@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;
}
答案 1 :(得分:10)
根据this,您应该返回binding.getRoot()
。
View getRoot ()
返回与之关联的布局文件中最外面的View 捆绑。如果此绑定用于合并布局文件,则将返回 合并标记中的第一个根。
答案 2 :(得分:1)
完成这里是kotlin变体:
val binding = convertView?.tag as? CheckBinding ?: CheckBinding.inflate(layoutInflater, parent, false)
binding.check = this.getItem(position)
binding.root.tag = binding
return binding.root
答案 3 :(得分:1)
使用生成的Binding类而不是DataBindingUtil类。参见Documentation.
如果您正在
Fragment
,ListView
或RecyclerView
适配器,您可能更喜欢使用inflate()
绑定类
binding = CheckBinding.inflate(this, parent, false);
binding = DataBindingUtil.inflate(
LayoutInflater.from(getContext()),
R.layout.check, parent, false);
其他代码与@sergi相同
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CheckBinding binding;
if(convertView == null) {
binding = CheckBinding.inflate(this, parent, false);
convertView = binding.getRoot();
}
else {
binding = (CheckBinding) convertView.getTag();
}
binding.setCheck(this.getItem(position));
convertView.setTag(binding);
return convertView;
}
答案 4 :(得分:0)
ItemTickFilterBinding mFilterBinding;
if (convertView==null) {
mFilterBinding= DataBindingUtil.inflate(
LayoutInflater.from(mContext),
R.layout.item_tick_filter, parent, false);
convertView.setTag(mFilterBinding);
}
else {
mFilterBinding=(ItemTickFilterBinding)convertView.getTag();
}
答案 5 :(得分:0)
DataBindingUtil将把ViewDataBinding对象保存到view.tag,以便稍后可以通过DataBindingUtil.getBinding(convertView)检索它
on:
push:
branches:
- $default-branch