【问题标题】:Android + ListView background sets background while scrolling?Android + ListView 背景在滚动时设置背景?
【发布时间】:2011-09-29 22:05:48
【问题描述】:

我有一个通过 ArrayAdapter 填充的 ListView。在适配器中,我根据条件设置视图背景颜色。它可以工作,但是在滚动其余行时采用这种颜色。这是一些代码:

class DateAdapter extends ArrayAdapter<DateVO> {
    private ArrayList<DateVO> items;
    public ViewGroup listViewItem;

    //constructor
    public DateAdapter(Context context, int textViewResourceId, ArrayList<DateVO> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            if (view == null) {
                LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.row, null);
            }

            final DateVO dateItem = items.get(position);

            if (dateItem != null) {

                //is this my issue here? does position change while scrolling?
                if(items.get(position).getField().equals("home")){
                    view.setBackgroundResource(R.drawable.list_bg_home);
                }
                ...
            }

        }catch (Exception e) {
            Log.i(ArrayAdapter.class.toString(), e.getMessage());
        }

        return view;
    }
} 

【问题讨论】:

    标签: android


    【解决方案1】:

    这是 ListView 的默认行为。可以通过将 cacheColorHint 设置为透明来覆盖它。 只需添加,

    android:cacheColorHint="#00000000"
    

    在您的 xml 文件中。

    更多详情,您可以浏览ListView Backgrounds 文章。 摘录如下:

    要解决此问题,您只需禁用缓存颜色提示优化(如果您使用非纯色背景),或者将提示设置为适当的纯色值。您可以使用 android:cacheColorHint 属性从代码(请参阅 setCacheColorHint(int))或最好从 XML 中执行此操作。要禁用优化,只需使用透明色#00000000。以下屏幕截图显示了在 XML 布局文件中设置了 android:cacheColorHint="#00000000" 的列表

    编辑:作为 convertView 传递的视图本质上是一个视图,它是列表视图的一部分,但不再可见(由于滚动)。所以它实际上是您创建的视图,并且可能是您为其设置了自定义背景的视图。要解决此问题,只需确保在不满足条件时重置背景。像这样:

    if(condition_satisfied) {
        //set custom background for view
    }
    else {
        //set default background for view
        convertView.setBackgroundResource(android.R.drawable.list_selector_background);
    }
    

    基本上,如果您的条件不满足,您将不得不撤消当您的条件满足时所做的任何自定义,因为您可能收到了一个旧的自定义视图convertView。 这应该可以解决您的问题。

    【讨论】:

    • 感谢您的帖子,但 cacheColorHint 不是我的问题,见上文。
    • 天才!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 2017-05-22
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多