您可以对线性布局使用 weightsum = 3,对每个按钮使用 layout_weight = 1。查看详细代码。我希望这将有所帮助。祝你好运 :)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
layout.setWeightSum(3);
for (int i = 0; i < 3; i++) {
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnParams.weight = 1.0f;
Button btn = new Button(this);
btn.setText("Btn");
btn.setLayoutParams(btnParams);
layout.addView(btn);
}
setContentView(layout);
}
}
或者这个代码更好但更复杂^^
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
mainLayout.setLayoutParams(params);
mainLayout.setWeightSum(3);
for (int i = 0; i < 3; i++) {
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setText("Btn");
btn.setLayoutParams(btnParams);
LinearLayout childLayout = new LinearLayout(this);
LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
childParam.weight = 1.0f;
childLayout.setLayoutParams(childParam);
childLayout.setGravity(Gravity.CENTER);
childLayout.addView(btn);
mainLayout.addView(childLayout);
}
setContentView(mainLayout);
}
}