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);
}
I had just the same problem but found a somewhat different solution.
And if you find out what to use for "fill_parent" (hint try -1) then you may use those constants for width and height.
I don't know why, but when moving top and left edges the Android keeps the right and bottom edges in same place. As I could not change the width and height properly (the image was disappearing), I've used this:
I don't know if it's the best way, but worked for me. I've tested it in 2.2+ and works fine!
You must import android.widget.LinearLayout.LayoutParams; because the default is ViewGroup's LayoutParams (by Davit T)
the above answers are right.but this one would be more perfect
In response to your comment on Mayra's answer, I had a similar issue with RelativeLayout instead of AbsoluteLayout. The solution was to use a similar method and cast it as your layout type. Something like this:
It took me forever to figure this out so I wanted to post it here for someone else if they needed it.
Use the version of addView that takes LayoutParams: