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

别说谁变了你拦得住时间么 提交于 2019-12-01 15:29:21

问题


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:

  • Try different conversions because maybe the problem is related to the difference of densities between the Bitmap and the Layout:

    Resources r = getResources();
    float x = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, r.getDisplayMetrics());
    
  • Try to use different methods in the layout to set the margins:

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.leftMargin = (int) newPosition.x;
    params.topMargin = (int) newPosition.y;
    element.setLayoutParams(params);
    
  • I also wanted to use the options available for the RelativeLayout in XML but I really cant find it programmatically but I can find the way to specify the dimension, I mean:

    android:layout_marginLeft ="50px" // or "50mm", or dp, or inches...
    

回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/6025872/using-relativelayout-dynamically-and-setting-margins-in-px-dp-inch-mm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!