【问题标题】:How to set margin for ImageView in pixels in android java?如何在android java中以像素为单位设置ImageView的边距?
【发布时间】:2017-01-07 23:03:48
【问题描述】:

我有一组 ImageView,其 BackgroundResource 和 LayoutParams 将在单独的 xml 文件中定义。高度、宽度、marginleft 和 margintop 以像素为单位。这些值是相对于 1024x600 像素分辨率的屏幕而言的。我正在使用的代码

    ImageView ImgV= (ImageView)findViewById(R.id.ImgV_1);
    RelativeLayout.LayoutParams the_dimens = new RelativeLayout.LayoutParams(50,50);
    the_dimens.setMargins(800,50,0,0);

    ImgV.setBackgroundResource(R.drawable.bulbon);
    ImgV.setLayoutParams(the_dimens);

虽然高度和宽度似乎以像素为单位正确显示,但边距却不是。那么如何设置边距值以应用像素而不是以下代码采用的任何默认单位。 the_dimens.setMargins(800,50,0,0);

该应用程序仅适用于 1024x600 设备,因此我不担心与分辨率无关的设计。 谢谢。

【问题讨论】:

  • ViewGroup.MarginLayoutParams 的官方文档说:setMargins(int left, int top, int right, int bottom) Sets the margins, in pixels. [...]
  • @pskink 我已经检查并测量了 Photoshop 中的值。他们不加起来
  • @pskink 如果它没有在模拟器中正确显示(即 1024x600 res),我怀疑实际设备中会出现这种情况。我想我在这里错过了一些东西..
  • @pskink 你是对的。这是我的错。根相对布局有填充。我想在发帖之前我应该​​更加小心。谢谢你的时间:)
  • 真的没问题

标签: java android android-layout android-studio margin


【解决方案1】:

check this

int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels

【讨论】:

    【解决方案2】:

    你可以这样做:

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(left, top, right, bottom);
    imageView.setLayoutParams(lp);
    

    【讨论】:

      猜你喜欢
      • 2013-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多