【问题标题】:android ImageView setPadding has no effectandroid ImageView setPadding 没有效果
【发布时间】:2012-01-27 20:21:31
【问题描述】:

我正在尝试设置 ImageView 的填充。我的代码在下面

private void createEpisodeView() {
    float scale = this.getResources().getDisplayMetrics().density;
    int padding = (int) (PADDING * scale + 0.5f);

    rlItemsRoot = (LinearLayout) findViewById(R.id.rl_items_root);

    for (int i = 0; i < GameLevels.TOTAL_EPISODES; i++) {
        ImageView iv = new ImageView(this);

        iv.setPadding(padding, padding, padding, padding);          
        iv.setBackgroundResource(R.drawable.icon_small);

        rlItemsRoot.addView(iv);
    }

}

但它没有效果。但是当我在 XML 中设置它时,它看起来很好。

【问题讨论】:

  • 当我们动态设置填充时,填充默认以像素表示。在 xml 中使用相同的值 px 或 dip
  • 我在 XML 中使用 dip,在这里我将 pix 转换为 DIP。而 5 常量是取消转换为 int 的效果。即 0.7 在 int 中为 0,但如果添加 0.5 则不会。

标签: android imageview padding


【解决方案1】:

你注意到自己正在使用的一个

iv.setBackgroundResource(R.drawable.icon_small);

这将为 ImageView 设置背景。背景图像将填充整个视图,因为它位于视图中所有内容的后面。

使用

iv.setImageResource(R.drawable.icon_small);

改为。

【讨论】:

  • 谢谢,我很高兴我不需要在 imageview 周围做不必要的线性布局包装来获得填充!
【解决方案2】:

而不是设置

iv.setBackgroundResource(R.drawable.icon_small);

设置

iv.setImageResource(R.drawable.icon_small);

问题解决了:)

如果有人知道原因,请回复。

【讨论】:

  • 当您设置背景时,您的内边距会丢失。你必须在设置背景之后setPadding(..),而不是之前。 setBackgroundDrawable(..) 的文档中指出了这一点,但 Google 忽略了 setBackgroundResource(..) 的提及。
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2018-05-30
相关资源
最近更新 更多