Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 529
Bresiu Avatar asked Oct 10 '13 06:10

Bresiu


People also ask

How do you set linear layout weight programmatically?

To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1" .


1 Answers

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.

like image 168
ssantos Avatar answered Sep 21 '22 16:09

ssantos