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

梦想与她 提交于 2019-12-01 15:50:09
Shreyash Mahajan

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.

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

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.

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