你如何被动地改变列表视图中单个项目的背景?

How do you passively change the background of a single item in a listview?

我正在编写一段代码,其中包含列表视图中列出的时间表。意图是在某个时间之间更改列表视图中某个项目的背景。例如,当它的 3:40 时,表示 3:00-4:00 的项目将具有绿色背景,而当它变为 4:00 时,背景将变回白色。关于如何做到这一点的任何想法?到目前为止,这是我的相关代码。

    final ListView schedule = (ListView) findViewById(R.id.schedule);
    String[] myKeys = getResources().getStringArray(R.array.friday_schedule);
    schedule.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myKeys));
    Calendar c = Calendar.getInstance();
    final int hour = c.get(Calendar.HOUR);
    if(hour<6&&hour>5)
    {
        schedule.item(0).setBackgroundColor(Color.CYAN);
    }

也供参考,这是一个与this类似的问题。如果我忘了附上我的一些代码,请告诉我。谢谢!

考虑创建一个覆盖 getView()ArrayAdapter 的子 class。 getView() 会有这样的逻辑:

...
final ListView schedule = (ListView) findViewById(R.id.schedule);
String[] myKeys = getResources().getStringArray(R.array.friday_schedule);
schedule.setAdapter(new ScheduleAdapter(this, android.R.layout.simple_list_item_1, myKeys));
...

public static class ScheduleAdapter extends ArrayAdapter<String> {

    public ScheduleAdapter(Context context, int resource, String[] schedule) {
        super(context, resource, schedule);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = super.getView(position, convertView, parent);
        // compare current clock hour to the hour this item represents
        boolean isCurrentHour = position == ... <your logic goes here>
        view.setBackgroundResource(isCurrentHour ? R.color.current_hour : R.color.normal_hour);
        return view;
    }

}

然后,在整点,在适配器上调用 notifyDataSetChanged()ListView 将重新绘制并更改颜色。

这里我将 ScheduleAdapter 显示为 activity 的内部 class 和 ListView