簡體   English   中英

Android + ListView背景在滾動時設置背景?

[英]Android + ListView background sets background while scrolling?

我有一個ListView,它通過ArrayAdapter填充。 在適配器中,我根據條件設置視圖背景顏色。 它可以工作,但滾動剩余的行時采用這種顏色。 這是一些代碼:

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

這是ListView的默認行為。 可以通過將cacheColorHint設置為transparent來覆蓋它。 只需添加,

android:cacheColorHint="#00000000"

在您的xml文件中。

有關更多詳細信息,您可以閱讀ListView背景文章。 這是一段摘錄:

要解決此問題,您所要做的就是禁用緩存顏色提示優化,如果使用非純色背景,或將提示設置為適當的純色值。 您可以使用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 那應該可以解決你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM