按钮边距的布局问题

Ant*_*nte 18 layout android android-layout

我在android aplication中组织布局有问题.我正在动态创建按钮并将这些代码添加到我的布局中:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

我将它添加到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>
Run Code Online (Sandbox Code Playgroud)

我正在导入这个.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"/>
Run Code Online (Sandbox Code Playgroud)

好吧,布局总是这样结束:在此输入图像描述

而不是像这样的东西(甚至按钮,方形按钮之间的间距): 在此输入图像描述

总结一下:我必须:

  • 在xml中描述按钮
  • 动态生成N个按钮
  • 将描述按钮的属性添加到动态创建的按钮
  • 组织布局,以便它可以在buttonList中均匀分布按钮,并在tham之间留出空格

ada*_*amp 53

记住,android:layout_*属性是LayoutParams.它们是父级的参数,并影响父级在该视图上执行布局的方式.您在layout_margin按钮上指定属性,但它们会被忽略.原因如下:

由于LayoutParams特定于父视图类型,因此当您使用布局中的顶级视图上的LayoutInflater或其他layout_属性来扩展布局时,需要提供正确父类型的实例.(inflater不知道LayoutParams要生成什么类型.)

由于buttonList您是按钮视图的预期父级,因此请将您的inflate行更改为:

btn = (Button) layoutInflater.inflate(R.layout.button, buttonList, false);
Run Code Online (Sandbox Code Playgroud)

  • ups,抱歉,我错过了方法调用中的"假":)谢谢,解决了我的问题! (5认同)
  • 嗯,我认为这根本不是问题. (4认同)
  • 很高兴听见!:)`inflate`的返回值根据是否将膨胀的视图附加到第二个参数中指定的父级而不同.第三个可选的boolean参数指定如果膨胀的视图不为空,是否应该将其添加到父视图中,并且默认为"true".(是的,这很烦人,我们很抱歉.:))参考:http://goo.gl/ak6z8 (2认同)