我在 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"/>
Well, layout always ends up like this:
Instead of something like this (even spce between buttons, square buttons):
总结一下:我必须:
- 在 xml 中描述按钮
- 动态生成N个按钮
- 将描述的按钮的属性添加到动态创建的按钮中
- 组织布局,以便它可以均匀分布buttonList中的按钮,按钮之间有空格
记住,android:layout_*
属性是LayoutParams
。它们是父级的参数,影响父级在该视图上执行布局的方式。你指定layout_margin
按钮上的属性,但它们被忽略了。原因如下:
Since LayoutParams
特定于父视图类型,当您使用LayoutInflater
要不然layout_
布局中顶级视图上的属性将被删除。 (充气机不知道什么类型LayoutParams
来生成。)
Since buttonList
是按钮视图的预期父级,更改您的inflate
对此行:
btn = (Button) layoutInflater.inflate(R.layout.button, buttonList, false);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)