我有一个ListView有两个TextViews。我正在尝试将背景图像动态设置为TextViews. 根据每个项目/行的类别,我有大约 18 个不同的图像要显示。图像被命名为"abc1","abc2"等。这是我的自定义代码CursorAdapter:
private class MyListAdapter extends SimpleCursorAdapter {
public MyListAdapter(Context context, int layout, Cursor cursor, String[] from, int[] to) {
super(context, layout , cursor, from, to);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the resource name and id
String resourceName = "R.drawable.abc" + cursor.getString(7);
int resid = context.getResources().getIdentifier(resourceName,"drawable",context.getPackageName());
// Create the idno textview with background image
TextView idno = (TextView) view.findViewById(R.id.idno);
idno.setText(cursor.getString(3));
idno.setBackgroundResource(resid);
// create the material textview
TextView materials = (TextView) view.findViewById(R.id.materials);
materials.setText(cursor.getString(1));
}
}
当我在调试中运行它时,resid总是返回0表示找不到资源。resourceName看起来正确,id : "R.drawable.abc1"。我将图像文件导入到res/drawable文件夹中,它们列在R.java.
这是解决这个问题的正确方法还是有人有更好的解决方案?