我创建了一个带有自定义适配器的 ListView,它扩展了 SimpleAdapter。第五个是粉红色的。当我上下滑动时,其他项目会随机获得与第五个相同的背景颜色。
我觉得很奇怪,这是为什么呢?
截图:
截图1:启动后的应用程序
截图2:我上下滑动几次后的应用程序
文件:
MainActivity.java:
package com.example.test;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
public class MainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Car> cars = getData();
ListAdapter adapter = new CarListAdapter(this, cars, android.R.layout.simple_list_item_2, new String[] {
Car.KEY_MODEL, Car.KEY_MAKE }, new int[] { android.R.id.text1, android.R.id.text2 });
this.setListAdapter(adapter);
}
private List<Car> getData() {
List<Car> cars = new ArrayList<Car>();
for(int i = 0; i < 15; i++) {
cars.add(new Car("Car "+i, i+""));
}
return cars;
}
}
CarListAdapter.java:
package com.example.test;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
public class CarListAdapter extends SimpleAdapter {
private List<Car> cars;
private int[] colors = new int[] { 0x30ff2020, 0x30ff2020, 0x30ff2020 };
@SuppressWarnings("unchecked")
public CarListAdapter(Context context,
List<? extends Map<String, String>> cars, int resource,
String[] from, int[] to) {
super(context, cars, resource, from, to);
this.cars = (List<Car>) cars;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position == 5) {
int colorPos = position % colors.length;
view.setBackgroundColor(colors[colorPos]);
}
return view;
}
}
汽车.java:
package com.example.test;
import java.util.HashMap;
public class Car extends HashMap<String, String> {
private static final long serialVersionUID = 12872473L;
public String make;
public String model;
public static String KEY_MAKE = "make";
public static String KEY_MODEL = "model";
public Car(String make, String model) {
this.make = make;
this.model = model;
}
@Override
public String get(Object k) {
String key = (String) k;
if (KEY_MAKE.equals(key))
return make;
else if (KEY_MODEL.equals(key))
return model;
return null;
}
}
活动主.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="@android:id/list" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:visibility="visible"/>
</LinearLayout>