如果您使用AbsoluteLayout(我知道它已经被弃用了,但这是解决我的问题的唯一方法),您可以给子视图添加标签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);
}
params.x
andparams.y
seems like they are deprecated forRelativeLayout
- ThunderWiring