Skip to content Skip to sidebar Skip to footer

How Can I Get Images Dynamically From Drawable Folder?

I'm getting images by statically given the name like {R.drawable.image1,R.drawable.image2,R.drawable.image3} If I have some 50 images I cant give each and every file name in array

Solution 1:

This solution feels a little bit hacky not only because it uses reflection but also because it relies heavily on being able to recognize your own drawable resources by matching their names against a certain pattern (so you should try to use really unique names for the pictures)

That being said, you can change your code as follows:

Keep the private int[] image; but initialize it in the Adapter's constructor:

SwipeAdapter(Context cx){
    this.cx=cx;
    buildImageArray();
}

with a new method (note: you have to import java.lang.reflect.Field;)

privatevoidbuildImageArray() {

    // this will give you **all** drawables, including those from e.g. the support libraries!
    Field[] drawables = R.drawable.class.getDeclaredFields();
    SparseIntArray temp = new SparseIntArray();
    int index = 0;
    for (Field f : drawables) {
        try {
            System.out.println("R.drawable." + f.getName());
            // check the drawable is "yours" by comparing the name to your name pattern// this is the point where some unwanted drawable may slip in,// so you should spend some effort on the naming/ matching of your picturesif (f.getName().startsWith("image")) {
                System.out.println("R.drawable." + f.getName() + "==========================================");
                int id = cx.getResources().getIdentifier(f.getName(), "drawable", cx.getPackageName());
                temp.append(index, id);
                index++;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    image = newint[index];
    for (int i = 0; i < index; i++) {
        image[i] = temp.valueAt(i);
    }
}

Solution 2:

If all your drawables have names like: image1, image2, image3, .... then you can get their resource ids like this:

int i = 1; // get the id of image1int resId = context.getResources().getIdentifier("image" + i, "drawable", context.getPackageName());

and use it:

imageView.setImageResource(resId);

for this to work you have to provide a valid Context (inside an activity you can use this).

Solution 3:

Change the constructor of your adapter class like below. Just add image list as a parameter

publicclassSwipeAdapterextendsPagerAdapter {
privateArrayList<Integer> image;

privateContext cx;

SwipeAdapter(Context cx, ArrayList<Integer> image){

    this.cx=cx
    this.image =image
}

@Overridepublic int getCount() {
    return image.size;
}

@OverridepublicbooleanisViewFromObject(@NonNull View view, @NonNullObjectobject) {
   return (view==(RelativeLayout)object);
}

 @SuppressLint("SetTextI18n")
 @NonNull@OverridepublicObjectinstantiateItem(@NonNull ViewGroup     container, int position) {

   LayoutInflater layoutInflater = (LayoutInflater)      cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert layoutInflater != null;
View view=   layoutInflater.inflate(R.layout.page_fragment,container,false);
ImageView imageView=  view.findViewById(R.id.imageView);
imageView.setImageResource(image[position]);
container.addView(view);
return view;
}

@OverridepublicvoiddestroyItem(@NonNull ViewGroup container,     int position, @NonNullObjectobject) {
container.removeView((RelativeLayout) object);
} 

Instantiate adapter with image list as follw. In order to loop among image in drawable resource needs to add index in its name in order 1 to 50 if you want 50 images in your adapter

 ArrayList<Integer> images=new ArrayList<Integer>()
 for(int i =0;i<50; i++){
 int res = getResources().getIdentifier("<your pakecgename>:drawable/abc"+i, null, null);
 images.add(res);
}
SwipeAdapter adapter = new SwipeAdapter(activity, images)

Post a Comment for "How Can I Get Images Dynamically From Drawable Folder?"