如何将资产文件夹中的图像设置为列表视图?

我有一个名为images1 的资产文件夹,其中有 114 张图像。我需要用 2 个 textViews 和 1 个 imageView 在 listView 中设置它们。我对 textViews 没有问题,但我不知道如何将图像从资产设置为 listView。 我试过了:


int ids[] = new int[114];


for (int i = 0; i <ids.length; i++) {//<-------- taking ids of all pictures from images1 in assets-folder

        try {

            String[] images =getAssets().list("images1");

            ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

            int imgId = getResourceId(this, listImages.get(i),"images1", getPackageName());

            ids[i] = imgId;

        }

        catch(IOException ex) {}

    }


ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(

            questionTexts.length);//<--------filling listView's textViews and imageView

    Map<String, Object> m;

    for (int i = 0; i < questionTexts.length; i++) {

        m = new HashMap<String, Object>();

        m.put(ATTRIBUTE_QUESTION_TEXT, questionTexts[i]);//<-------- textView

        m.put(ATTRIBUTE_ANSWER_TEXT, answerTexts[i]);//<-------- textView

        m.put(ATTRIBUTE_NAME_IMAGE, ids[i]);//<-------- imageView

        data.add(m);

        String[] from = { ATTRIBUTE_QUESTION_TEXT, ATTRIBUTE_ANSWER_TEXT,

                ATTRIBUTE_NAME_IMAGE };

        int[] to = { R.id.listView_item_title, R.id.listView_item_short_description, R.id.listView_image };

        SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.item,

                from, to);

        lvSimple = (ListView) findViewById(R.id.lvSimple);

        lvSimple.setAdapter(sAdapter);

    }


但最后我有白色的田野而不是我的照片。 我知道当你的图片在 R.drawable 中时如何解决这个问题,但是当它们在资产子文件夹中时如何解决?


潇潇雨雨
浏览 136回答 3
3回答

Cats萌萌

你可以用这个。try&nbsp;{&nbsp; &nbsp; // get input stream&nbsp; &nbsp; InputStream ims = getAssets().open("avatar.jpg");&nbsp; &nbsp; // load image as Drawable&nbsp; &nbsp; Drawable d = Drawable.createFromStream(ims, null);&nbsp; &nbsp; // set image to ImageView&nbsp; &nbsp; mImage.setImageDrawable(d);&nbsp; ims .close();}catch(IOException ex)&nbsp;{&nbsp; &nbsp; return;}

蛊毒传说

Simple Adapter 只能使用 drawable-folder 或 Uri 中的 ID。但是您可以使用 ViewBinder 使用 setImageBitmap 方法设置图像。

智慧大石

你确定这个图片应该在assets/文件夹内吗?为什么不进去res/drawables/?当然,您可以从资产加载它;)要获取资产文件夹中所有文件的列表,请使用以下代码:list = getAssets().list("images1")要从资产加载图像,您可以使用以下代码:fun setImageFromAsset(ImageView view, String filename) {&nbsp;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; InputStream is = getAssets().open(filename);&nbsp; &nbsp; &nbsp; &nbsp; Drawable drawable = Drawable.createFromStream(is, null);&nbsp; &nbsp; &nbsp; &nbsp; view.setImageDrawable(drawable);&nbsp; &nbsp; }&nbsp; &nbsp; catch(IOException ex) {&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java