Adam Schmit
Adam Schmit

Reputation: 201

Using RelativeLayout dynamically and setting margins in px, dp, inch, mm

My application is just a modified ImageViewer with the options of zooming and dragging. Containing that modified Imageviewer there is a RelativeLayout (that I want to use as an AbsoluteLayout).

Then, new elements can be added to the layout to situate them in certain points of the image. The position (x, y) in pixels of the elements is in a database so I guess there is no other way that adding them programmatically, and not with XML.

Then the position of those elements is updated every time that a dragging or zooming action is performed.

The problem is that somehow the pixels of the image are not matching with the pixels in the RelativeLayout! So the items are "more or less" situated but not in the proper place (the further from (0,0) the bigger is the error).

Things I've tried already:

Upvotes: 9

Views: 33960

Answers (3)

Shreyash Mahajan
Shreyash Mahajan

Reputation: 23596

You can set the height, width and the margin by below code:

//headView
RelativeLayout.LayoutParams head_params = (RelativeLayout.LayoutParams)headView.getLayoutParams();
head_params.setMargins(80, 0, 0, 0); //substitute parameters for left, top, right, bottom
head_params.height = 60; head_params.width = 200;
headView.setLayoutParams(head_params);

Where headView is the view of your app.

Upvotes: 20

Lavanya
Lavanya

Reputation: 3913

Try this: for Relative Layout you can set the margins like this: params.setMargins(left, top, right, bottom);

Upvotes: 4

Adam Schmit
Adam Schmit

Reputation: 201

I've found the answer, the problem was in fact with the density, so I made:

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float density = metrics.density;
    //And then I add a new element like: realX*density, realY*density

I don't understand so much what it is doing but it works... Actually what I don't understand the value metrics.density Any explanation is welcome.

Upvotes: 3

Related Questions