SANDHYA
SANDHYA

Reputation: 791

How to add a view to another in android?

Is there any way to add a view to another at specified place? i.e I want to add a child view at (x, y) location of parent view. Please help me.

  parentView.addView(childView);

Upvotes: 1

Views: 1369

Answers (2)

Leon Lucardie
Leon Lucardie

Reputation: 9730

You can do this by using the LayoutParams in a RelativeLayaout

An example:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.leftMargin = 50; //Your X coordinate
params.topMargin = 60; //Your Y coordinate
parentView.addView(childView,params);

Upvotes: 5

Aleks G
Aleks G

Reputation: 57306

You can't add a view at (x,y) location of the parent. However you can trick it to achieve something like this:

  1. Have your parent be RelativeLayout

  2. Define your child view with android:layout_alignParentLeft="true", android:layout_alignParentTop="true", android:layout_marginLeft="X" android:layout_marginTop="Y" (or define the same things via code using LayoutParams)

  3. Add your child to your parent: parentView.addView(childView)

Upvotes: 0

Related Questions