2017-05-25 28 views
0

這可能是一個禁忌,但我試圖動態地將視圖添加到RecyclerView中。用例是以列表格式顯示不同數量的填字格。假設單元格的默認大小是一些任意數字:100.但是,如果單元格數量的長度大於容器的寬度,則單元格需要縮小以便它們適合。 screenshot of the incorrect behavior爲什麼RecyclerView ViewBinder返回不一致的寬度

我在想,解決方案然後是將容器的寬度除以單元格的數量,並將其設置爲視圖的寬度,然後將充氣視圖添加到容器中。

public class MyViewHolder extends RecyclerView.ViewHolder { 
    public static final int MAX_WIDTH = 200; 
    LayoutInflater layoutInflater; 
    LinearLayout cellHolder; 
    TextView someText; 

    public MyViewHolder(View view) { 
     super(view); 
     layoutInflater = LayoutInflater.from(view.getContext()); 
     someText = (TextView) view.findViewById(R.id.sometext); 
     cellHolder = (LinearLayout) view.findViewById(R.id.cell_container); 
    } 

    public void bind(Integer integer) { 
     someText.setText(integer.toString()); 
     cellHolder.removeAllViews(); 
     int totalWidth = cellHolder.getWidth(); 
     Log.e("WHY", String.format("bind: Why does this width calculation not consistently work? %d", totalWidth)); 

     int minWidth = totalWidth/integer; 
     if (minWidth == 0 || minWidth > MAX_WIDTH) { 
      minWidth = MAX_WIDTH; 
     } 
     for(int i = 0; i < integer; i++) { 
      View inflate = layoutInflater.inflate(R.layout.box, null); 
      inflate.setMinimumHeight(minWidth); 
      inflate.setMinimumWidth(minWidth); 

      TextView textView = (TextView) inflate.findViewById(R.id.square_number); 
      textView.setText(String.valueOf(integer)); 
      cellHolder.addView(inflate); 
     } 
    } 
} 

我已經創建了一個示例應用程序以準確顯示發生了什麼。 Here是在github上的示例應用程序中演示問題的整個代碼。我已經嘗試添加measure calls,並添加一個tree observer

回答

1

我可以修復您的項目!
enter image description here

要約束雙方的尺寸和你的盒子最大寬度,同時分享他們的父母的LinearLayout的寬度均勻,如果他們填補它。對於前兩種,你需要一個簡單的自定義的ViewGroup:

public class SquareWithMaxSize extends FrameLayout { 

public static final int MAX_WIDTH = 200; 

public SquareWithMaxSize(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

@Override 
protected void onMeasure(int widthSpec, int heightSpec) { 
    int width = Math.min(MeasureSpec.getSize(widthSpec), MAX_WIDTH); 
    int side = MeasureSpec.makeMeasureSpec(width, 
      MeasureSpec.EXACTLY); 
    super.onMeasure(side, side); 
} 
} 

替代,對於你的盒子的FrameLayout,然後在你的ViewHolder膨脹他們,給每個人平等的layout_weight。可以了,好了!

for(int i = 0; i < integer; i++) { 
     View inflate = layoutInflater.inflate(R.layout.box, null); 
     LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, minWidth); 
     lp.weight = 1; 
     inflate.setLayoutParams(lp); 

     TextView textView = (TextView) inflate.findViewById(R.id.square_number); 
     textView.setText(String.valueOf(integer)); 
     cellHolder.addView(inflate); 
    } 

遺憾地說,我不知道爲什麼你所得到的孩子的不一致性測量,但是我希望你不關心嗎:)

+0

作品像一個冠軍,謝謝! – farkerhaiku

相關問題