从资源创建新对象并修改它会更改资源

时间:2013-06-06 06:37:36

标签: android resources drawable transparent alpha

我有以下问题。

我有两个片段,每个片段都有一个带适配器的ListView。通过从第一个列表中选择元素,我将包含第一个列表的片段替换为包含第二个列表的片段。我想让每一行背景只在第二个片段中透明,但是下面的代码在第二个适配器的getView中使用,看起来它更新了资源?谁有人解释为什么?

代码:

First Fragment:

public View getView(int position, View convertView, ViewGroup parent) {
(...)
    v.setBackgroundResource(R.drawable.abstract_gray);
(...)
}

第二段片段:

public View getView(int position, View convertView, ViewGroup parent) {
(...)
    Drawable backgroundDrawable = context.getResources().getDrawable(R.drawable.abstract_gray);
    backgroundDrawable.setAlpha(ToolsAndConstants.BACKGROUND_TRANSPARENCY);
    v.setBackgroundDrawable(backgroundDrawable);
    // I call this to check if when I call the drawable from resurce it will not be transparent
    v.setBackgroundResource(R.drawable.abstract_gray);
    // But it is...So previous fragment background, when I go back with back Button
(...)
}

也许这个问题非常基本,但是当我从资源创建新的对象时,我实际上使用资源本身,对新对象所做的所有更改都会影响整个应用程序,即使其他类无法访问该对象? ?

编辑:

对不起,我刚才意识到我没有创建新的Drawable,我只是做了一个参考。那我怎么创建新的?如果我不能,我怎样才能改变第二个列表的背景?

1 个答案:

答案 0 :(得分:1)

Marek阅读了这篇文章,它解释了您的疑虑http://android-developers.blogspot.com/2009/05/drawable-mutations.html

相关问题