我有一个在xml中的LinearLayout:
<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" />
我想动态生成几个LinearLayout,并将它们等间距地放置在"progress"中,例如:
- 第一个LinearLayout将占据所有空间。
- 第二个LinearLayout将与第一个LinearLayout共享50%的空间
- 第三个LinearLayout将与第一个和第二个LinearLayout共享33%的空间
- 以此类推...
每个LinearLayout都将具有随机背景颜色。 我写了类似这样的代码:
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);
当用户按下按钮时,将生成另一个带有不同颜色的LL。我的方法不起作用。布局中没有背景颜色。
也许有另一种更简单的方法来实现进度条,使颜色在相等的空间中共享?
setBackgroundColor
不像 R.color.turquoise 期望一个 colorResId,而是这个颜色的实际值,你可以通过getResources().getColor(R.color.turquoise)
获取它。试着返回getResources().getColor(colors[getNextRandomInt(0, colors.length)]);
。 - ssantosgetNextRandomColor
方法,并从Activity
中调用getResources().getColor()
。我正在编辑我的答案。 - ssantos