setBackgroundResource() 丢弃了我的 XML 布局属性 [英] setBackgroundResource() discards my XML layout attributes

查看:28
本文介绍了setBackgroundResource() 丢弃了我的 XML 布局属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,它被用作 ListView 中的一个项目.在我的自定义适配器中,我使用 View.setBackgroundResource() 根据项目在列表中的位置更改视图的背景.(对于列表中的第一项和最后一项,我有单独的资产.)

I have a view which is used as an item in a ListView. In my custom adapter, I change the background of the view using View.setBackgroundResource() depending on the item's position in the list. (I have separate assets for the first and last items in the list.)

这会按预期设置正确的背景图像,但它具有令人讨厌的副作用,即我在视图的 XML 定义中设置的所有填充都被完全忽略了.

This sets the correct background image as expected, but it has the nasty side-effect that all the padding I'd set in the XML definition of the view is completely ignored.

(如果我在 XML 中设置背景可绘制对象,并且不要尝试在运行时在适配器中更改它,则填充都可以正常工作.)

(If I set the background drawable in the XML, and don't try to vary it at runtime in the adapter, the padding all works fine.)

如何更改背景图像并保留填充?这是一个错误吗?

How can I alter the background image, and retain the padding? Is this a bug?

编辑似乎其他人在这里发现了同样的问题:改变背景是否也会改变LinearLayout的填充?

EDIT it seems someone else has found the same problem here: Does changing the background also change the padding of a LinearLayout?

推荐答案

我也遇到了这个问题.大概您正在使用可绘制的 LayerList 资源?这就是我正在使用的.不幸的是,我没有找到修复它的真正"方法,这似乎是代码中的一个错误,但我没有追究它.但是,我很幸运,因为在我的视图已经正确渲染之后我设置了错误"背景,所以只需在设置背景后保存然后恢复填充值,例如:

I ran into this issue as well. Presumably you're using a LayerList resource drawable? That's what I was using. Unfortunately, I found no "real" way of fixing it, it seems like a bug in the code, but I didn't chase it down. However, I was lucky in the sense that I was setting the "buggy" background after my view had already been rendered properly, so it was just a matter of saving then restoring the padding values after the background is set, e.g:

  if(condition) {
    int bottom = theView.getPaddingBottom();
    int top = theView.getPaddingTop();
    int right = theView.getPaddingRight();
    int left = theView.getPaddingLeft();
    theView.setBackgroundResource(R.drawable.entry_bg_with_image);
    theView.setPadding(left, top, right, bottom);
  }

作为替代方案,您不必使用之前的 padding 值,也可以使用尺寸值:

As an alternative, you don't have to use the previous values of padding, you can also use a dimension value:

  int pad = resources.getDimensionPixelSize(R.dimen.linear_layout_padding);
  theView.setBackgroundResource(R.drawable.entry_bg_with_image);
  theView.setPadding(pad, pad, pad, pad);

这篇关于setBackgroundResource() 丢弃了我的 XML 布局属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆