If you use an AbsoluteLayout (I know that it is deprecated, but it was the only way to solve my problem) you can give the childViews the tag android:layout_x
and android:layout_y
to set their absolute position within the AbsoluteLayout
.
However I don't want to set these information in the xml, because I only know them at runtime. So how can I set these parameters at runtime programmatically? I don't see any method on the View like view.setLayoutX(int x)
or something.
Here is my XML, which works fine, when I set the layout_x
and layout_y
values:
<?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>
In fact, I don't want to set any button within the xml anymore, but rather retrieve some information via remote and add buttons depending on that information.
Here is the part the code I'm using so in my onCreateMethod
to add these buttons:
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);
}
Use the version of addView that takes LayoutParams:
LayoutParams params = mLayout.generateLayoutParams();
params.x = remoteObject.x;
params.y = remoteObject.y;
mLayout.addView(button, params);