如果您使用 AbsoluteLayout(我知道它已被弃用,但这是解决我的问题的唯一方法),您可以给 childViews 标签android:layout_x
并android:layout_y
在AbsoluteLayout
.
但是我不想在 xml 中设置这些信息,因为我只在运行时知道它们。那么如何在运行时以编程方式设置这些参数呢?我在 View 上看不到任何方法之类的view.setLayoutX(int x)
东西。
这是我的 XML,当我设置layout_x
和layout_y
值时,它工作正常:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="@drawable/myImageView"
android:layout_width="1298px"
android:layout_height="945px"
android:layout_x="0px"
android:layout_y="0px" />
<Button
android:id="@+id/myButton1"
android:text="23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50px"
android:layout_y="300px"
android:tag="23"/>
<Button
android:id="@+id/myButton2"
android:text="48"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50px"
android:layout_y="300px"
android:tag="48"/>
</AbsoluteLayout>
事实上,我不想再在 xml 中设置任何按钮,而是通过远程检索一些信息并根据该信息添加按钮。
这是我onCreateMethod
在添加这些按钮时使用的代码部分:
for (MyRemoteObject remoteObject: list) {
Button button = new Button(this);
button.setOnClickListener (listener);
button.setTag(remoteObject.id);
button.setText(remoteObject.id);
// button.setLayoutX(remoteObject.x) ????
// button.setLayoutY(remoteObject.y) ????
myLayout.addView(button);
}