按钮边距的布局问题 [英] Layout problem with button margin
问题描述
我在 android 应用程序中组织布局时遇到问题.我正在动态创建按钮并使用此代码将它们添加到我的布局中:
I have problem with organizing layout in android aplication. I'm dynamically creating buttons and adding them with this code to my layout:
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:
I'm adding it to the 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,我在其中定义按钮布局:
and i'm importing this .xml where i'm defining button layout:
<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 中均匀分布按钮,并在 tham 之间留有空格
推荐答案
记住,android:layout_*
属性是 LayoutParams
.它们是父级的参数,会影响父级在该视图上执行布局的方式.您正在按钮上指定 layout_margin
属性,但它们被忽略了.原因如下:
Remember, android:layout_*
attributes are LayoutParams
. They are arguments to the parent and affect how the parent will perform layout on that view. You're specifying layout_margin
attributes on your buttons, but they're getting ignored. Here's why:
由于 LayoutParams
特定于父视图类型,因此在使用 LayoutInflater
或其他 扩展布局时,您需要提供正确父类型的实例布局中顶层视图的 layout_
属性将被删除.(inflater 不知道要生成什么类型的 LayoutParams
.)
Since LayoutParams
are specific to the parent view type, you need to supply an instance of the correct parent type when you inflate layouts using a LayoutInflater
or else layout_
attributes on the top-level view in the layout will be dropped. (The inflater would have no idea what type of LayoutParams
to generate.)
由于 buttonList
是按钮视图的预期父级,请将 inflate
行更改为:
Since buttonList
is your intended parent for the button views, change your inflate
line to this:
btn = (Button) layoutInflater.inflate(R.layout.button, buttonList, false);
这篇关于按钮边距的布局问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!