我在该适配器中使用简单光标适配器创建一个列表视图我从SQlite获取我的标题列现在我想将图像从Drawable文件夹添加到同一适配器到标题字段我们如何使用SimpleCursorAdapter.ViewBinder执行此操作
这是我的代码
protected void onCreate(Bundle savedInstanceState) {
final int[] imageResource = new int[]{R.drawable.juice,R.drawable.medicinebowl,R.drawable.kam};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView= (ListView) findViewById(R.id.listView);
dbHelper = new SqlLiteDbHelper(this);
try {
dbHelper.openDataBase();
} catch (SQLException e) {
e.printStackTrace();
}
sqLiteDatabase = dbHelper.getReadableDatabase();
cursor = dbHelper.gettitles(sqLiteDatabase);
String[] from = new String[]{dbHelper.TITLE};
int[] to = new int[]{R.id.title};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.title_row, cursor, from, to);
adapter.notifyDataSetChanged();
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
switch (view.getId()) {
case R.id.circle:
int imageType = cursor.getInt(columnIndex);
int imageToBeShown = 0;
switch (imageType) {
case 0:
imageToBeShown = imageResource[0];
break;
case 1:
imageToBeShown = imageResource[0];
break;
case 2:
imageToBeShown = imageResource[0];
break;
}
((ImageView) view).setImageResource(imageToBeShown);
return true;
}
return false;
}
});
listView.setAdapter(adapter);
我的数据库类
public Cursor gettitles(SQLiteDatabase db)
{
db = this.getReadableDatabase();
Cursor cursor;
cursor = db.query(true, "record", new String[]{TITLE,ITEMNO + " as _id"}, null, null, TITLE, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
自定义布局
<ImageView
android:layout_width="90dp"
android:layout_height="190dp"
android:layout_marginLeft="10dp"
android:id="@+id/circle"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text "
android:id="@+id/title"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
style="@android:style/TextAppearance.Medium"
android:textColor="#FFFFFF"
android:layout_toRightOf="@+id/circle"
android:layout_centerHorizontal="true"
/>