2017-04-30 35 views
0

例如像我在回收我嘗試做以下是否可以爲recyclerview提供動態模板?

return new TransactionViewHolder(rowTemplate); 

可這一工作的viewholder創建一個視圖

LinearLayout rowTemplate = new LinearLayout(getContext()); 

呢? 。通常我們做以下操作:

return new TransactionViewHolder(((RelativeLayout) inflater.inflate(R.layout.employee_item, parent, false))); 

我不確定如何以RV的方式膨脹視圖,以便RV可以將此行模板附加到自身中。我實際上正在計劃做這樣的事情,並想知道是否有人有任何提示

+0

它可以工作嗎?當你嘗試時發生了什麼? – nasch

+0

不,它沒有。但是有一個非常簡單的解決方法。 –

+0

只用一個根膨脹一個空的項目佈局。對視圖的構造函數做一個新的重載,它將這個動態視圖和充氣視圖一起使用。然後在構造函數中說inflatedview.addview(dynamicview)。 Id將代碼發佈爲您想要的答案 –

回答

0

沒有inflater.inflate(viewResource,parent,false)它不會工作。原因是,即使我們已經創建了一個視圖,它也會成爲一個孤兒,在RV中浮動,因爲我們沒有將它附加到RV的父級。

這裏是一個很好的解決辦法,其保持完好房車回收以及具有所期望的行爲

// Create new views (invoked by the layout manager) 
@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, 
                int viewType) { 

    LayoutInflater inflater = LayoutInflater.from(parent.getContext()); 
    if (viewType == TYPE_TRANSACTION) { 
     return new TransactionViewHolder(((RelativeLayout) inflater.inflate(R.layout.transaction_item, parent, false)), ((LinearLayout) createRowTemplate(templateTransaction))); 
    } else { 
     return new LoadHolder(inflater.inflate(R.layout.load_item, parent, false)); 
    } 
} 

在TransactionViewHolder構造函數執行以下操作。

public TransactionViewHolder(RelativeLayout rowRootView, LinearLayout rowTemplate) { 
      super(rowRootView); 
      this.rowRootView = rowRootView; 
      this.rowRootView.addView(rowTemplate); 

      rowRootView.setOnClickListener(this); 
     } 
相關問題