我想以编程方式将三个线性布局添加到每个相同宽度的活动中。问题是我无法以编程方式设置这些布局的权重。我可以在xml中执行此操作,但我想在程序中执行此操作。 这就是我想要的:
答案 0 :(得分:43)
这是解决方案
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
lp.weight = 1;
请参阅完整解决方案
LinearLayout ll1, ll2, ll3;
/* Find these LinearLayout by ID
i.e ll1=(LinearLayout)findViewById(R.id.ll1);
*/
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
lp.weight = 1;
ll1.setLayoutParams(lp);
ll2.setLayoutParams(lp);
ll3.setLayoutParams(lp);
答案 1 :(得分:6)
在将布局参数设置为子视图时使用new LinearLayout.LayoutParams(int width, int height, float weight)
设置权重
答案 2 :(得分:3)
这样做..
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtNote = (LinedEditText) findViewById(R.id.txtNote);
lnr = (LinearLayout) findViewById(R.id.lnr);
LinearLayout l1 = new LinearLayout(this);
LinearLayout l2 = new LinearLayout(this);
LinearLayout l3 = new LinearLayout(this);
l1.setBackgroundResource(android.R.color.holo_green_light);
l2.setBackgroundResource(android.R.color.holo_orange_dark);
l3.setBackgroundResource(android.R.color.holo_blue_bright);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT, 1);
lnr.addView(l1, param);
lnr.addView(l2, param);
lnr.addView(l3, param);
}
答案 3 :(得分:2)
您可以通过为各个线性布局设置布局权重属性,在LinearLayout - LayoutParams构造函数中传递它:
LinearLayout.LayoutParams param = new LinearLayout.LayoutParam(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1);
或
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
0,
LayoutParams.MATCH_PARENT, 1);
希望它可以帮到你!