如何将资源文件夹中的图像加载到android listview中

时间:2012-06-02 12:00:46

标签: java android android-listview

我在资源文件夹中有200张图片,我将其命名为name_1.pngname_2.png。我有一个数组,因为我有一些数字,例如2, 4 , 6 ,30 , 40 ... and so on

我想将图片和文本视图加载到android listview中,并根据资源文件夹中的数字显示图片。

为此,我为activity class创建了image adapter classcustom list view

我可以根据数组数据显示text view数据,但不能显示图像。

任何人都可以建议我如何做到这一点。我想我必须用getview方法编写代码来改变图像。

这是我尝试的getview方法

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    convertView = mInflater.inflate(mViewResourceId, null);


    TextView tv1 = (TextView)convertView.findViewById(R.id.tvtype);
    TextView tv2 = (TextView)convertView.findViewById(R.id.tvnumber);
    ImageView i1= (ImageView)convertView.findViewById(R.id.ivlfirst);
    //int i = Integer.parseInt("normal_"+mStrings.get(position)+".png");

i1.setBackgroundResource("normal_"+mStrings.get(position)+".png");
    tv1.setText(mStrings1.get(position));
    tv2.setText(mStrings.get(position));
    return convertView;
}

5 个答案:

答案 0 :(得分:0)

当图像位于res文件夹中时,您无法轻松完成此操作,因为每个资源都由int id访问。

您应该考虑将图像放入您可以像常规文件系统一样访问的资源文件夹中。看一下AssetManager。

答案 1 :(得分:0)

如果您想从assets获取图片,请尝试此操作:

InputStream is = ctx.getAssets().open("normal_"+mStrings.get(position)+".png");
Drawable d = Drawable.createFromStream(is, "resourceName");
i1.setBackgroundDrawable(d); //i1 is your imageView
希望它有所帮助!!

答案 2 :(得分:0)

只需按照下面的 getView()方法

进行操作即可
 String yourimagename="normal_"+ mStrings.get(position);   // In this no need of image extension like .png,.jpg etc

 int  resImgId= YourActivityName.this.getResources().getIdentifier("Your Package Name:drawable/" +yourimagename, null, null);  

或试试这个

 int  resImgId= YourActivityName.this.getResources().getIdentifier("Your Package Name:drawable/" +yourimagename, null, null); 

或试试这个

 int  resImgId= context.getResources().getIdentifier("Your Package Name:drawable/" +yourimagename, null, null); 
 i1.setImageResource(resImgId);

答案 3 :(得分:0)

如果要根据其名称使用drawable文件夹中的图像(从资源名称获取资源ID),请使用 public int getIdentifier(String name,String defType,String defPackage)它返回给定资源名称的资源标识符,如:

 int image = getResources().getIdentifier(image_name, "drawable",getPackageName());
 ImageView i1= (ImageView)convertView.findViewById(R.id.ivlfirst);
 i1.setBackgroundResource(image);

对于您的特定情况,您可以使用:

i1.setBackgroundResource(getResources().getIdentifier("normal_"+mStrings.get(position), "drawable",getPackageName()));

答案 4 :(得分:0)

Integer array取一R.drawable.imageView1......200并传递其值

    private Integer[] Imgid = {R.drawable.imageview1,....,200  };
    i1.setBackgroundResource(Imgid[j]);