0

我想根据 ListView 行的数据设置背景颜色。我实现了一个 ListActivity,但我不知道如何通知加载完成,以便我可以访问 ListView 的行。

public class RouteList extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.route_list);

    CommuteDb db = new CommuteDb(this);
    Cursor cursor = db.getRouteList();
    ListAdapter adapter = new SimpleCursorAdapter(this, // Context.
        R.layout.route_row, //row template
        cursor, // Pass in the cursor to bind to.
        new String[] { BaseColumns._ID, "Name" }, //Columns from table
        new int[] { R.id.id, R.id.name }, //View to display data
        0); //FLAG_REGISTER_CONTENT_OBSERVER

    setListAdapter(adapter);

    ListView listView = (ListView) findViewById(android.R.id.list);
    Log.i("RouteList","listView.getChildCount()=" + listView.getChildCount()); //returns always 0
//Loop will not execute because no row yet
    for (int i=0; i < listView.getChildCount(); i++) {
        View rowView = listView.getChildAt(i);
        Log.i("RouteList",rowView.getClass().getName());
        rowView.setBackgroundColor(0x88ff0000);
    }

如果我稍后执行此循环(例如根据用户的请求),我可以获取每一行并分配我想要的颜色。但是,在 ListView 中加载数据后,我需要自动执行此操作。

4

1 回答 1

0

谢谢你的提示。
以这种方式修改代码后它可以工作:我添加了一个从 SimpleCursorAdapter 派生的自定义适配器(RouteAdapter):

private class RouteAdapter extends SimpleCursorAdapter {

    public RouteAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to, int flags) {
        super(context, layout, c, from, to, flags);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //Let the default getView do the job (inflate the row layout and set views to their values from database  
        View view = super.getView(position, convertView, parent);
        //Get the resulting view (route_row) and do custom loading
        TextView isOffer = (TextView) view.findViewById(R.id.isOffer);
        if (isOffer.getText().equals("0"))
                view.setBackgroundColor(0x8800ff00); //seek=green
            else
                view.setBackgroundColor(0x88ff0000); //offer=red

        return view;
    }
}

然后在我的原始代码中,我刚刚用 RouteAdapter 替换了 SimpleCursorAdapter:

ListAdapter adapter = new RouteAdapter(this, // Context.
于 2013-02-20T05:46:33.213 回答