Android线性布局重量编程

我想以编程方式将三个线性布局添加到每个相同宽度的活动中。 问题是我无法以编程方式设置这些布局的权重。 我可以在xml中执行此操作,但我想在程序中执行此操作。 这就是我想要的: 在此处输入图像描述

    这是解决方案

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

    查看完整解决方案

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

    希望它可以帮到你!