最好的辦法是保持一個數據項的國王,並使用陣列適配器,使它們,您可以更改通知,並設置適當的顏色,因爲它渲染。
的你以後完整的例子是在這裏:
public class TestStuff extends Activity {
private class KingItem {
public KingItem(String name, String description) {
this.name = name;
this.description = description;
this.hexColor = "#000000";
}
public String name;
public final String description;
public String hexColor;
}
private List<KingItem> kings = new ArrayList<TestStuff.KingItem>();
private ListView kingsList;
private ArrayAdapter<String> kingAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
kings.add(new KingItem("Henry IV(1)", "Description form Henry IV(1)"));
kings.add(new KingItem("Henry V", "Description for Henry V"));
kings.add(new KingItem("Henry VIII", "Description for Henry VIII"));
kings.add(new KingItem("Richard II", "Description for Richard II"));
kingsList = (ListView) findViewById(R.id.list);
if (kingAdapter == null) {
kingAdapter = new KingsListAdapter(this, this, android.R.layout.simple_list_item_1, new ArrayList<String>());
}
kingAdapter.clear();
kingsList.setAdapter(kingAdapter);
kingsList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView desc = (TextView) TestStuff.this.findViewById(R.id.text);
KingItem king = kings.get(position);
desc.setText(king.description);
king.hexColor = "#0000ff";
for (int i=0; i<position; i++) {
kings.get(i).hexColor = "#ff0000";
}
for (int i=position+1; i<kings.size(); i++) {
kings.get(i).hexColor = "#000000";
}
kingAdapter.notifyDataSetChanged();
}
});
for (KingItem king : kings) {
kingAdapter.add(king.name);
}
kingAdapter.notifyDataSetChanged();
}
private class KingsListAdapter extends ArrayAdapter<String> {
private final Activity activity;
private final int textViewResourceId;
public KingsListAdapter(Activity activity, Context context, int textViewResourceId, List<String> kingsNames) {
super(context, textViewResourceId, kingsNames);
this.activity = activity;
this.textViewResourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(textViewResourceId, null);
}
KingItem kingItem = kings.get(position);
TextView text1 = (TextView) v.findViewById(android.R.id.text1);
text1.setText(kingItem.name);
v.setBackgroundColor(Color.parseColor(kingItem.hexColor));
return v;
}
}
}
這將每一個項目渲染到當前選定爲紅色,選擇一個藍色,當前選定項目後,任何事情都會發生回到黑色背景。
注意我只是將KingItem設置爲正確的顏色,然後告訴列表重新渲染。沒有必要得到意見,或父母,並嘗試巧妙地設置背景。相反,我將這些信息保存在KingItem中,並使適配器變得非常簡單。
PLZ添加您的getView()代碼 – 2011-06-04 06:27:57