您可以使用weightsum = 3 linearlayout和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);
}
}
如何使每個單元具有相同的寬度? – omega