1

ListView に問題があります。listView の 1 つおきの要素を設定して、背景を透明にしたいと考えています。次のコードを使用します。

public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ViewHolder holder;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.list_row_object, null);

            Drawable backgroundDrawable = context.getResources().getDrawable(R.drawable.abstract_gray);
            if((int)(position%2)==1)
                backgroundDrawable.mutate().setAlpha(ToolsAndConstants.BACKGROUND_TRANSPARENCY);

            // It is not working sometimes when I just use v.setBackground(backgroundDrawable); here. Why?
            v.setBackground(backgroundDrawable.mutate());

            holder = new ViewHolder();
            holder.rowNumber = (TextView) v.findViewById(R.id.list_row2_number);
            holder.character = (TextView) v.findViewById(R.id.list_row2_char);
            holder.strokesNumber = (TextView) v.findViewById(R.id.list_row2_strokes_number);
            v.setTag(holder);
        }
        else
            holder = (ViewHolder)v.getTag();

        (...)
        (...)
        (...)
        return v;
    }

リストは正常に読み込まれますが、問題は、上下に数回スクロールすると完全に狂ってしまうことです (?Randomly? は透明な背景と無地の背景を設定します)。以下のスクリーンショットを参照してください (スクロール前後)。

前:

ここに画像の説明を入力

後:

ここに画像の説明を入力

アダプタークラスの外で、フラグメントを別のものに置き換える onClickListener を追加するだけです。onScrollListenerなどはありません。なぜレイアウトが変わっているのですか?

4

1 に答える 1

1

これは、リスト アイテムのビューが再利用されるためです。convertView が null の場合だけでなく、getView メソッドが呼び出されるたびに背景をリセットする必要があります。例えば

public View getView(int position, View convertView, ViewGroup parent)
     ....
     if (v == null) {
         // Inflate the view without set the background
     }

     // Set the background based on position
     ...
}
于 2013-06-07T01:15:01.557 に答える