2016-11-11 82 views
2

我有一个Android活动,从适配器类中的可观察列表中提取其数据。如何在列表视图中使用Android DataBinding并仍使用ViewHolder模式?

getView()在我的适配器类的方法是:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    if (inflater == null) { 
     inflater = (LayoutInflater) parent.getContext() 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    // Perform the binding 
    ActivityTeamMessageListRowBinding binding = DataBindingUtil.inflate(inflater, R.layout.my_activity_list_row, parent, false); 
    binding.setInfo(list.get(position)); 
    binding.executePendingBindings(); 

    // Return the bound view 
    return binding.getRoot(); 
} 

来完成这项工程。然而,我看到Android的警告无条件布局通胀从视图适配器ActivityTeamMessageListRowBinding binding ...线。

我一直在研究ViewHolders来解决这个问题,但我似乎无法弄清楚如何做到这一点,仍然使用我的数据绑定。据推测,列表越长,我就会看到不使用ViewHolder的性能越差。

有谁知道如何扩展我的getView(...)代码以合并视图活页夹?我在我的my_activity_list_row.xml中有3 TextView s和1 ImageView

回答

12

试试这个:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    if (inflater == null) { 
     inflater = ((Activity) parent.getContext()).getLayoutInflater(); 
    } 

    // Perform the binding 

    ActivityTeamMessageListRowBinding binding = DataBindingUtil.getBinding(convertView); 

    if (binding == null) { 
     binding = DataBindingUtil.inflate(inflater, R.layout.my_activity_list_row, parent, false); 
    } 

    binding.setInfo(list.get(position)); 
    binding.executePendingBindings(); 

    // Return the bound view 
    return binding.getRoot(); 
} 

我还没有使用的数据与ListView(我将使用RecyclerView)结合,但即兴,这是我想尝试。使用断点或日志记录来确认,当convertView不是null时,您从getBinding()返回binding更多时候(也可能是所有时间—我对数据绑定的缓存工作原理感到朦胧)。

+0

'ViewHolder'如何适应这种模式? – Brett

+2

@Brett:'ActivityTeamMessageListRowBinding' *是视图持有者。数据绑定框架为您提供的一部分是代码生成视图持有者。根据ID值,您将在类中映射到“R.layout.my_activity_list_row”中的小部件的字段。请参阅[文档](https://developer.android.com/topic/libraries/data-binding/index.html#views_with_ids)。 – CommonsWare

+0

啊,好的!我不知道。我在这里学到了东西!谢谢! – Brett

相关问题