Dan Chaltiel
Dan Chaltiel

Reputation: 8494

Views with different width but same weight

In an horizontal LinearLayout, I want to spread evenly a lot of textviews (I'd says my max is 120 for now).

For now, I do it by setting the weightsum to 120, then adding 120 textviews with a wheight of 1f.

Here is my simplified code for you to test :

LinearLayout layout = new LinearLayout(context);
layout.setWeightSum(120);
for (int i = 0; i < 120; i++) {
    TextView tv = new TextView(context);
    tv.setLayoutParams(new LinearLayout.LayoutParams(0, 100, 1f));
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Dan", "onClick: getWidth="+v.getWidth());
        }
    });
    layout.addView(tv);
}

On my Genymotion Nexus 4 emulator, I get 2 situations :

The final use of all this is that some TV sometimes weight more. Please note that except for this little bug, I get the very exact graphic result I want :-)


Questions :

  1. Why do do my TV are not the same width (I'd accept 1 or 2 for completing the total width) ?
  2. How can I resolve this bug ?
  3. Is LinearLayout the optimal layout for me to do what I want ?

Upvotes: 0

Views: 63

Answers (1)

chessdork
chessdork

Reputation: 2029

This behavior is exactly as expected. On the Nexus 4 emulator in portrait, you have 772px. You want to split this evenly between 120 views.

floor(772 / 120) = 6

If each view took 6 pixels, this would take up 720 pixels (120 x 6), leaving you 52 left over. So your options are to leave a 52px gap at the end, or to add an extra 1px on 52 of the views. The latter is what is happening currently.

The only way for you to resolve this issue is to pick a number of views that can exactly divide the number of pixels on the screen. For example, if your screen width was 700px, 100 views that are 7px would fit perfectly.

Upvotes: 1

Related Questions