编辑使用linearLayout创建的Android按钮的位置

编辑使用linearLayout创建的Android按钮的位置,android,android-linearlayout,Android,Android Linearlayout,我正在尝试动态创建按钮,它们将具有不同的大小和位置。 我有代码创建一个大小不同的按钮,但我一直在改变位置。 我正在使用linearlayout并尝试使用setMargins来移动按钮,但它似乎正在更改按钮内的边距。我的代码如下: public void button(int a, int b) { newButton = new Button(this); newButton.setText("HELLO"); LinearLayout.LayoutParams la

我正在尝试动态创建按钮,它们将具有不同的大小和位置。 我有代码创建一个大小不同的按钮,但我一直在改变位置。 我正在使用linearlayout并尝试使用setMargins来移动按钮,但它似乎正在更改按钮内的边距。我的代码如下:

public void button(int a, int b) {

    newButton = new Button(this);
    newButton.setText("HELLO");

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.setMargins(0, 0, 0, 0); 

    ViewGroup.LayoutParams params = layout.getLayoutParams();
    params.width = a;
    params.height = b;
    layout.requestLayout();

    layout.addView(newButton, layoutParams);

}
这是我对该位的清单:

 <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="58dp"
    android:layout_toRightOf="@+id/textView1"
    android:text="Button" />

  <LinearLayout
    android:id="@+id/layout"
    android:layout_width="50sp"
    android:layout_height="40sp"
    android:orientation="vertical" >
  </LinearLayout>

您了解什么是线性布局以及为什么要使用它吗?布局的每个子级都将捕捉到位。如果我有一个垂直的线性布局,它有3个孩子,他们将在彼此之上。我可以改变它们的重力,使它们被吸引到不同的边缘,但要“改变”它的位置是不可能的,这取决于你所说的“改变”是什么意思


查看其他布局。您可能需要使用相对值。为什么不使用button.setX(float x)和button.setY(float y)?您需要使用RelativeLayout而不是LinearLayout。它更简单,但只有在api 11之后才可用…

直到您指出它,我才明白这一点。谢谢你的回复,我感谢你的帮助。我会调查一下相对位置,我会试试看。谢谢你的回复我感谢你的帮助我很高兴这是有用的!请将答案设为正确答案