Android线性布局权重以编程方式

我想将三个线性布局以编程方式添加到每个相同宽度的活动中。 问题是我不能以编程方式设置这些布局的权重。 我可以在XML中做到这一点,但我想在程序中做到这一点。 这是我想要的: 在这里输入图像说明

Solutions Collecting From Web of "Android线性布局权重以编程方式"

这里是它的解决scheme

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100); lp.weight = 1; 

查看完整解决scheme

 LinearLayout ll1, ll2, ll3; /* Find these LinearLayout by ID ie 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); 

使用new LinearLayout.LayoutParams(int width, int height, float weight)来设置权重时,设置布局参数的子视图

这样做..

 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); } 

你可以通过为你的单独线性布局设置布局权重属性,在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); 

希望它可以帮助你!