tags:

views:

144

answers:

2

I want to add a view inside a FrameLayout programmatically and to place it in a specific point within the layout with a specific width and height. Does FrameLayout support this? If not, should I use an intermediate ViewGroup to achieve this?

int x; // Can be negative?
int y; // Can be negative?
int width;
int height;
View v = new View(context);
// v.setLayoutParams(?); // What do I put here?
frameLayout.addView(v);

My initial idea was to add an AbsoluteLayout to the FrameLayout and place the view inside the AbsoluteLayout. Unfortunately I just found out that AbsoluteLayout is deprecated.

Any pointers will be much appreciated. Thanks.

A: 

The thread here on stackOverflow at

http://stackoverflow.com/questions/2965662/how-do-you-setlayoutparams-for-an-imageview

covers it somewhat.

For instance: LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30); yourImageView.setLayoutParams(layoutParams);

implies that you need to be defining a LinearLayout.LayoutParams (or in your case a FrameLayout.layoutParams) object to pass to the setLayoutParams method of your v object.

At

http://developer.android.com/reference/android/widget/FrameLayout.html

it almost makes it looks like you could ask your v to:

generateDefaultLayoutParams () via this method if you have not defined the parameters specifically.

But it's late, and those links are making my eyes bleed a little. Let me know if they nhelp any :-)

Quinn1000
A: 

From the link Quinn1000 provided:

You can add multiple children to a FrameLayout, but all children are pegged to the top left of the screen.

This means you can't put your View at a specific point inside the FrameLayout (except you want it to be at the top left corner :-)).

If you need the absolute positioning of the View, try the AbsoluteLayout:

A layout that lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less flexible and harder to maintain than other types of layouts without absolute positioning.

As for setting the width and height of the View, also like Quinn1000 said, you supply the v.setLayoutParams() method a LayoutParams object, depending on the container you chose (AbsoluteLayout, LinearLayout, etc.)

Matthias Schippling
Unfortunately AbsoluteLayout is deprecated.
hgpc
You're right. I missed that when I looked at the API earlier. I guess you could play with margin-left/top for your View inside a FrameLayout to get a similar experience to the AbsoluteLayout.
Matthias Schippling
How can I do that programmatically?
hgpc
Take a look at the API for the FrameLayout.LayoutParams (link is in my answer): It extends MarginLayoutParams which provides a "setMargins" method.
Matthias Schippling