动态使用RelativeLayout并设置px、dp、inch、mm的边距

9

我的应用程序是一个带有缩放和拖动选项的修改过的ImageViewer。

在包含这个修改后的ImageViewer的RelativeLayout中,我想要使用它作为AbsoluteLayout。

然后,可以向布局中添加新元素,以将它们定位在图像的某些点上。元素在数据库中的位置(x,y)以像素为单位,所以我猜只能通过编程方式添加它们,而不是使用XML。

然后,每次执行拖动或缩放操作时,这些元素的位置都会更新。

问题在于,图像的像素与RelativeLayout中的像素不匹配!因此,项目“更多或更少”地被放置在错误的位置上(距离(0,0)越远,误差就越大)。

我已经尝试过的事情:

  • 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...
    
3个回答

20

您可以使用以下代码设置高度、宽度和边距:

//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);

headView代表你的应用程序视图。


1
只是为了添加更多信息(我知道已经过去一年以上了)。根据文档[链接](http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html#setMargins(int,%20int,%20int,%20int)),需要调用`requestLayout()`来考虑边距。 - khose

4
尝试这个:对于相对布局,您可以像这样设置边距:params.setMargins(left, top, right, bottom);

你好Rosalie,这个方法的问题是我只想设置左边和上边的边距,而不是四个边距。 - Adam Schmit
2
好的,那么你可以将一些整数值传递给左侧和顶部,对于其他的可以给零。然后问题就解决了,我想。 - Lavanya

3
我找到了答案,问题实际上出现在密度上,所以我进行了以下操作:
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float density = metrics.density;
    //And then I add a new element like: realX*density, realY*density

我不太明白它在做什么,但它能正常运行...实际上,我不理解metrics.density的值是什么意思。欢迎任何解释。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接