如何将标签添加到从数据库填充的ListView?

时间:2018-01-13 07:27:58

标签: android listview

我有一个包含许多列的表,包括自动增量ID和主题名称。当我的活动加载时,ListView会填充表格中的一些主题。我正在寻找一种方法来将id作为标签添加到每个ListView项目上,这样即使有多个具有相同主题名称的条目,我也可以告诉您单击哪个项目。我目前的代码:

从表中获取主题:

public ArrayList getSubjects(int level){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor subjectCursor = db.rawQuery("select * from " + SUBJECTS_TABLE_NAME + " where " + SUBJECTS_COL_3 + "="+level,null);
    ArrayList<String> mArrayList = new ArrayList<String>();
    for(subjectCursor.moveToFirst(); !subjectCursor.isAfterLast(); subjectCursor.moveToNext()) {
        mArrayList.add(subjectCursor.getString(1));
    }
    return mArrayList;
}

设置ListView:

ArrayList<String> mArrayList = myDb.getSubjects(1);

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            this, R.layout.subject_list_item, mArrayList);
    lv.setAdapter(arrayAdapter);

    // listening to single list item on click
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // selected item
            String subject = ((TextView) view).getText().toString();

            // Launching new Activity on selecting single List Item
            Intent i = new Intent(getApplicationContext(), SubjectActivity.class);
            // sending data to new activity
            i.putExtra("subject", subject);
            i.putExtra("level", 1);
            startActivity(i);
        }
    });

ListView项目的XML:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="120dp"
android:textSize="30sp"
android:gravity="center"
android:background="@drawable/subject_back"
android:textColor="#ffffffff"
android:textStyle="bold" >

感谢您为我想要实现的目标提供任何建议或替代方案。

0 个答案:

没有答案