【问题标题】:Custom ListView from SQLite Cursor来自 SQLite 游标的自定义 ListView
【发布时间】:2014-07-11 23:58:21
【问题描述】:

我的列表包含具有 namestatus 的元素。名称是 Stringstatusint。 我想要一个ListView,其中每个元素都显示name 和一个用于选择status 的下拉菜单。此外,背景颜色将根据 status int 更改。


我有光标:

String[] ItemsData= { "id", "name", "status" };

Cursor ItemsCursor = ItemsDatabase.query(
    Database.ITEMS_TABLE, ItemsData, null, null, null, null, null
);

ItemsCursor.moveToFirst();

我已经创建了列表(以编程方式我必须这样做):

ListView ItemsListView = new ListView(this);

现在,我知道我可以使用和Adapter(如SimpleCursorAdapter)但我不知道该怎么做,考虑到nameString 内的TextView status 是一个Spinner,预定义的值在数据库中保存为int,默认值是与status 对应的值。此外,status 也会改变背景颜色。

也许我不能使用Adapter。另外,如果可能的话,我不知道如何在每个列表元素中包含 Spinner

【问题讨论】:

  • 您应该在 xaml 中为 ListView 创建项目。 This教程可以帮到你
  • 我可以预料到让适配器为列表视图的每一行膨胀 DropDown 的复杂性。我宁愿建议一个对话框,该对话框包含下拉菜单,以便在点击单个列表元素时出现。
  • 对,我将放置一个按钮,该按钮必须包含与每个状态编号对应的文本。但是,如何让Cursor 将数字转换为String,然后再将其绑定到ListView

标签: android sqlite listview spinner android-adapter


【解决方案1】:

这是我的做法:

listV = (ListView) findViewById(R.id.viewTest);
ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();

int     i = 1;
String  value = null;
HashMap<String, String> map;
while ((value = database.getStuff(i)) != null) {
        map = new HashMap<String, String>();
        map.put("title", value);
        map.put("desc", "RANDOM TEXT");
        map.put("img", String.valueOf(R.drawable.images));
        listItem.add(map);
        i++;
    }

    SimpleAdapter s = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.list_content,
            new String[] {"img", "title", "desc"}, new int[] {R.id.img, R.id.stuff, R.id.stuff});
    listV.setAdapter(s);

这里是我处理游标的地方:

public String getStuff(int id) {
    Cursor c = db.rawQuery("SELECT value FROM test WHERE _id = " +id, null);
    return cursorToString(c);
}

private String cursorToString(Cursor c) {
    if (c.getCount() == 0)
        return null;
    c.moveToFirst();
    String s = c.getString(0);
    c.close();
    return s;
}

“R.layout.list_content”是用于设置列表中每个项目形状的 .xml 文件,您可以添加图像 TextView 以及您想要的所有其他内容!

如果您想了解更多关于 .xml 内容的信息,请告诉我

【讨论】:

    【解决方案2】:

    您可以使用 CursorAdapter 从您想要的任何布局构建行。

    public class CustomAdapter extends CursorAdapter {
    
        public CustomAdapter(Context context, Cursor c) {
            super(context, c, false);
        }
    
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return LayoutInflater.from(context).inflate(R.layout.row, parent, false);
        }
    
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Populate view with the cursor, add listeners...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多