How to programatically add LinearLayout with background color, and weight to another layout

Bresiu picture Bresiu · Oct 10, 2013 · Viewed 16.7k times · Source

I have LinearLayout in xml:

    <LinearLayout
        android:id="@+id/progress"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/progress_height"
        android:layout_alignParentBottom="true"
        android:baselineAligned="false"
        android:orientation="horizontal" />

and I would like to generate dynamically few another LinearLayouts and put them to "progress" equaly spaced, for example:

  • First LinearLayout added will occupy all the space.
  • Second LL will share 50% of the space with 1LL
  • Third LL will share 33% of the space with 1LL and 2LL
  • and so on...

Every LinearLayout will have random background color I wrote something like this:

mProgress = (LinearLayout) findViewById(R.id.progress);
.
.
.
LinearLayout prog = new LinearLayout(this);
            prog.setBackgroundColor(CommonUtils.getNextRandomColor());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);

            prog.setLayoutParams(params);
            mProgress.addView(prog);

When user press the buttons, another LL will generate, with different color.

My method doesn't work. There is no background color in layouts.

Maybe there is another much simpler method to achive some kind of progress bar with colors sharing some space equally?

Answer

ssantos picture ssantos · Oct 10, 2013

Double check that getNextRandomColor is returning something like.-

getResources().getColor(colorResId);

and not just a colorResId. If that's the case, you could try this.-

prog.setBackgroundColor(getResources().getColor(CommonUtils.getNextRandomColor()));

Anyway, if you're building a multicolor progress bar, you should consider changing the width of a single layout, and using a gradient color.