2017-05-25 5 views
0

これはいいえではないかもしれませんが、私はRecyclerViewにビューを動的に追加しようとしています。ユースケースは、さまざまな数のクロスワードセルをリスト形式で表示することです。しかし、セル数の長さがコンテナの幅より大きい場合、セルは収縮するように縮小する必要があります。 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の幅を共有しながら、寸法やあなたのボックスの最大幅の両方を制限したいです。あなたのボックスにFrameLayoutのために、そして、あなたのViewHolderでそれらを膨らませると、それぞれ等しいlayout_weight与えること

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); 
} 
} 

代替:最初の二つについて、あなたは単純なカスタムのViewGroupを必要としています。準備完了!あなたが子供の一貫性のない測定結果を得ている理由を私は知らないが、私はあなたはもう気にしない:)チャンピオンのような

+0

作品を願って、ありがとうと言って申し訳ありません

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); } 

! – farkerhaiku

関連する問題