我在Android应用程序中遇到了布局组织问题。我正在动态创建按钮,并使用此代码将它们添加到我的布局中:
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < NO_NUMBERS; i++){
Button btn = new Button(this);
btn = (Button) layoutInflater.inflate(R.layout.button, null);
btn.setId(2000+i);
Integer randomNumber = sort.getNumbersCopy()[i];
btn.setText(randomNumber.toString());
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
}
我正在将它添加到LinearLayout中:
<LinearLayout
android:id="@+id/buttonlist"
android:layout_alignParentLeft="true"
android:layout_marginTop="185dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
我正在导入这个 .xml 文件并在其中定义按钮布局:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:textSize="26dp"
android:textStyle ="bold"
android:textColor="#ffffff"
android:background="@drawable/button"
android:layout_marginLeft="8px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
布局总是变成这样:
而不是像这样(按钮之间有空格,按钮是正方形的):
总结一下,我需要:
- 在xml中描述按钮
- 动态生成N个按钮
- 将所描述的按钮属性添加到动态创建的按钮中
- 组织布局,使其可以平均分配buttonList中的按钮,并在它们之间添加空格
inflate
的返回值取决于它是否将充气视图附加到第二个参数中指定的父视图上。第三个可选布尔参数指定如果不为 null,则应将充气视图添加到父视图中,它的默认值为true
。(是的,这很烦人,我们很抱歉。 :))参考:http://goo.gl/ak6z8 - adamp