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;
    }
}

次に、元のコードで、SimpleCursorAdapter を RouteAdapter に置き換えました。

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