【发布时间】:2013-04-13 02:04:40
【问题描述】:
我在让我的程序正确显示 4 个按钮并排且宽度相同时遇到了重大问题。我尝试了一堆组合,并在 StackOverflow 搜索解决方案上花了一个多小时,但没有任何一个运气。我怎样才能让这四个按钮在垂直界面的同一行中都具有相同的高度?
这是我到目前为止没有运气的情况。按钮太大、太小或从宽度 0 开始隐藏。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
layout.setWeightSum(1);
Button redButton = new Button(this);
redButton.setText("Red");
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
0,
LayoutParams.WRAP_CONTENT,
0.25f);
redButton.setWidth(0);
redButton.setLayoutParams(p);
layout.addView(redButton);
Button greenButton = new Button(this);
greenButton.setText("Green");
greenButton.setLayoutParams(p);
greenButton.setWidth(0);
layout.addView(greenButton);
Button blueButton = new Button(this);
blueButton.setText("Blue");
blueButton.setLayoutParams(p);
blueButton.setWidth(0);
layout.addView(blueButton);
Button yellowButton = new Button(this);
yellowButton.setText("Yellow");
yellowButton.setLayoutParams(p);
yellowButton.setWidth(0);
layout.addView(yellowButton);
setContentView(layout);
}
【问题讨论】:
-
你为什么不使用 xml 呢?
-
尝试做一些不同的事情。我已经知道如何使用 XML 来实现,但我想以编程方式为我正在开发的应用程序进行布局,这需要一些动态布局的东西。
标签: android