我试图将Android的数据绑定功能与自定义适配器和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绑定= ListItemBinding.inflate(layoutInflater,viewGroup,false);/或ListItemBinding binding = DataBindingUtil.inflate(layoutInflater,R.layout.list_item,viewGroup,false);
发布于 2015-11-26 17:23:32
根据这,您应该返回binding.getRoot()。
View getRoot ()返回与绑定关联的布局文件中的最外层视图。如果此绑定用于合并布局文件,则将返回合并标记中的第一个根。
发布于 2016-03-23 10:11:12
但是,为了顺利滚动,您应该做以下操作。
@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;
}发布于 2017-11-24 13:46:47
要完成,这里是kotlin变体:
val binding = convertView?.tag as? CheckBinding ?: CheckBinding.inflate(layoutInflater, parent, false)
binding.check = this.getItem(position)
binding.root.tag = binding
return binding.roothttps://stackoverflow.com/questions/33943717
复制相似问题