改变的GradientDrawable在不同的地方被不必要地重用

时间:2015-09-18 18:47:39

标签: android layout drawable shapedrawable

我有一个ShapeDrawable drawable / my_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">
    <solid
       android:color="#FFFF00" />
    <padding android:left="1dp"
        android:top="1dp"
        android:right="1dp"
        android:bottom="1dp" />
</shape>

我在我的应用中的几个地方用作某些TextView的背景。就像在 layout / my_fragment.xml

中一样
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout...>
    <TextView
        android:id="@+id/tag"
        android:background="@drawable/my_drawable"
        android:layout_height="wrap_content"
        android:layout_width="wrap"
        android:text="Some text"
    />
<!-- other tags -->
</RelativeLayout>

或用作列表项的布局 layout / my_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout...>
    <TextView
        android:id="@+id/subject"
        android:background="@drawable/my_drawable"
        android:layout_height="wrap_content"
        android:layout_width="wrap"
    />
<!-- other tags -->
</RelativeLayout>

现在,当我在列表的ArrayAdapter内以编程方式更改形状的颜色时,我的应用中完全不同位置的片段内TextView的背景获取与我列表中最后一项相同的颜色!从那时起,具有改变颜色的形状将被用于其布局中具有my_fragment.xml的所有其他活动。

holder.subject = (TextView) v.findViewById(R.id.subject);

GradientDrawable bgShape = (GradientDrawable)holder.subject.getBackground();
bgShape.setColor( position % 2 == 0 ? Color.BLACK : Color.WHITE );

这怎么可能?我怎样才能避免“重用”行为?

以下是我的数组适配器的代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ViewHolder holder; // to reference the child views for later actions

    if (v == null) {
        LayoutInflater vi = 
            (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.my_list_item, null);
        // cache view fields into the holder
        holder = new ViewHolder();
        holder.subject = (TextView) v.findViewById(R.id.subject);
        // associate the holder with the view for later lookup
        v.setTag(holder);
    }
    else {
        // view already exists, get the holder instance from the view
        holder = (ViewHolder) v.getTag();
    }

    GradientDrawable bgShape = (GradientDrawable)holder.subject.getBackground();
    bgShape.setColor( position % 2 == 0 ? Color.BLACK : Color.WHITE );
    holder.subject.setText(getItem(position));
}

// somewhere else in your class definition
static class ViewHolder {
    TextView subject;
}