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

查看:283
本文介绍了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?

修改,似乎别人已经在这里发现了同样的问题:<一href="http://stackoverflow.com/questions/2886140/does-change-the-background-change-the-padding-of-a-linear-layout">Does改变背景也改变的LinearLayout的填充?

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

推荐答案

我就遇到了这个问题为好。您使用的是LayerList资源绘制presumably?这就是我所用。不幸的是,我发现修复它没有真正的方式,这似乎是在code中的错误,但我没有追下来。不过,我很幸运,因为我设置的越野车的背景后,我的观点已经被正确呈现的感觉,所以这是节约然后恢复填充值的背景设定后,只是早晚的问题,例如:

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

编辑: 作为一种替代方法,你不必使用填充的previous值,你也可以使用一个尺寸值:

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天全站免登陆