Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Khắc phục lỗi ListView nền đen khi cuộn (scroll) trên Android

Vấn đề

Khi cuộn ListView, nền các item bị chuyển sang màu đen (hoặc màu không mong muốn). Nguyên nhân: cacheColorHint mặc định là đen để tối ưu vẽ.

Giải pháp đơn giản

Thêm thuộc tính android:cacheColorHint trong XML Layout của ListView:

<ListView
    android:id="@+id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:cacheColorHint="#00000000" />

#00000000 = trong suốt (transparent). Hoặc đặt màu nền của item (ví dụ: #FFFFFF cho trắng).

Ví dụ hoàn chỉnh

activity_main.xml

<ListView
    android:id="@+id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:cacheColorHint="#00000000" />

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ListView list = findViewById(R.id.list);
        ArrayList arrayList = new ArrayList<>();
        // Thêm 24 item để đủ cuộn
        for (int i = 0; i < 4; i++) {
            arrayList.add("JAVA");
            arrayList.add("ANDROID");
            arrayList.add("C Language");
            arrayList.add("CPP Language");
            arrayList.add("Go Language");
            arrayList.add("AVN SYSTEMS");
        }
        
        ArrayAdapter adapter = new ArrayAdapter<>(
            this, android.R.layout.simple_list_item_1, arrayList
        );
        list.setAdapter(adapter);
        
        list.setOnItemClickListener((parent, view, position, id) -> {
            String item = (String) list.getItemAtPosition(position);
            Toast.makeText(this, item, Toast.LENGTH_LONG).show();
        });
    }
}

Kết quả

Cuộn ListView không còn nền đen:

Khắc phục lỗi ListView nền đen khi cuộn (scroll) trên Android Khắc phục lỗi ListView nền đen khi cuộn (scroll) trên Android

Giải thích kỹ thuật

  • cacheColorHint báo cho ListView biết màu nền của item để tối ưu rendering khi cuộn.
  • Mặc định là đen (#FF000000) → item trong suốt bị vẽ đen khi recycle.
  • Đặt #00000000 (transparent) hoặc màu nền thực tế của item.

Cách khác: Set trong code

list.setCacheColorHint(Color.TRANSPARENT); // hoặc Color.WHITE

Lưu ý

  • Vấn đề này chủ yếu trên ListView cũ. RecyclerView không gặp vấn đề này.
  • Nếu item layout có background color riêng, hãy set cacheColorHint trùng màu đó.