gpt4 book ai didi

android - 按钮边距的布局问题

转载 作者:IT老高 更新时间:2023-10-28 23:17:30 25 4
gpt4 key购买 nike

我在 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"/>

好吧,布局总是这样结束:enter image description here

而不是这样的东西(甚至按钮之间的spce,方形按钮): enter image description here

总结一下:我必须:

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

最佳答案

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

由于 LayoutParams 特定于父 View 类型,因此当您使用 LayoutInflater 扩展布局时,您需要提供正确父类型的实例布局中顶级 View 的 layout_ 属性将被删除。 (inflater 不知道要生成什么类型​​的 LayoutParams。)

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

btn = (Button) layoutInflater.inflate(R.layout.button, buttonList, false);

关于android - 按钮边距的布局问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5315529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com