2017-02-13 61 views
0

我正在創建自定義Layout在我的RecyclerView使用,唯一我無法弄清楚的是如何在我的自定義佈局中設置列表項目的寬度。 因爲每個列表項目都有不同的寬度。Android Studio RecyclerView項目寬度在自定義佈局

+0

Yo你可以保持列表項的寬度爲'wrap_content'。究竟是什麼問題? –

+0

列表項的寬度取決於我在適配器中獲得的數據,所以wrap_content不起作用 –

回答

0

如果你在你的自定義適配器使用Recycler.ViewHolder,你可以建立一個類來像

/**view halper class for recycler list item*/ 
public class MyViewHelper extends RecyclerView.ViewHolder { 
    public TextView tvtitle,tvdesc,tvtown,tvtype; 
    public ImageView thumbnail; 
    RelativeLayout rl; 

    public MyViewHelper (View view) { 
     super(view); 
     tvtitle = (TextView) view.findViewById(R.id.tvtitle); 
     tvdesc = (TextView) view.findViewById(R.id.tvdesc); 
     tvtown = (TextView) view.findViewById(R.id.tvtown); 
     tvtype = (TextView) view.findViewById(R.id.tvtype); 
     thumbnail = (ImageView) view.findViewById(R.id.thumbnail); 
     rl = (RelativeLayout) itemView.findViewById(R.id.rlClick); 
    } 
} 

擴展這個ViewHolder在oncreateview你可以創建並返回這個觀點

View itemView = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.offer_swap_cardview, parent, false); 
     return new MyViewHelper(itemView); 

這使您能夠在onBindView中獲取查看項目,並且可以相應地更改其高度

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {  
MyViewHolder myholder= (MyViewHolder)holder; 
myholder.tvtitle.setWidth(30);//in pixels 

}