2016-11-11 25 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

相關問題