我有一个数据库,我有两列 第一列的名称:Img 第二列的名称:名称 我想在Listview中显示它们 显示名称没有问题 但是显示图片有问题解决方案是什么?
Adbter Listview
public class adbter_listview extends ArrayAdapter<String> {
Activity activity;
ArrayList<Integer> icons;
ArrayList<String> name;
public adbter_listview(Activity activity, ArrayList<Integer> icons, ArrayList<String> name) {
super(activity, R.layout.custom_listview, name);
this.activity = activity;
this.icons = icons;
this.name = name;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
View v = inflater.inflate(R.layout.custom_listview, parent, false);
ImageView iv = (ImageView) v.findViewById(R.id.imageView);
TextView tv = (TextView) v.findViewById(R.id.textView);
iv.setImageResource(icons.get(position));
tv.setText(name.get(position));
return v;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView con;
ArrayList<String> icons_name = new ArrayList<>();
ArrayList<Integer> icons = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = (ListView) findViewById(R.id.con);
db connect = new db(MainActivity.this);
SQLiteDatabase read = connect.getReadableDatabase();
Cursor save = read.rawQuery("select image from game",null);
save.moveToFirst();
while(save.isAfterLast()==false)
{
icons_name.add(save.getString(0));
icons.add(R.drawable.user);
save.moveToNext();
}
adbter_listview adb = new adbter_listview(MainActivity.this,icons,name);
con.setAdapter(adb);
}
}
请帮帮我
答案 0 :(得分:0)
使用此行获取drawable的int id
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
在你的情况下
nameOfDrawable = save.getString(0);我想
然后添加到图标arrayList,
icons.add(drawableResourceId);
希望这会奏效。
答案 1 :(得分:0)
而不是这个
icons.add(R.drawable.user);
使用
icons.add(Integer.parseInt(save.getString(1)));
在适配器中它应该只在图像来自drawables文件夹并且像
一样使用时才有效R.drawable.icons.get(position)
但首先从oncreate mainThread调用中删除数据库调用到另一个线程。创建新线程或使用asynctask或使用加载器。不要在mainthread中进行sqlitedatabase调用。