【问题标题】:ListActivity ListView completed loadListActivity ListView 完成加载
【发布时间】:2023-04-02 20:53:01
【问题描述】:

我想根据 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 中加载数据后自动执行此操作。

【问题讨论】:

  • 你需要实现一个自定义的CursorAdapter
  • 在这种情况下,您可以使用自定义的 adpaters,在 getview 方法中,您可以检查数据并相应地设置背景颜色

标签: android android-listview listactivity


【解决方案1】:

感谢各位大侠的指点。
以这种方式修改代码后它可以工作: 我添加了一个从 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.

【讨论】:

    猜你喜欢
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2013-09-19
    相关资源
    最近更新 更多