1

I'm kinda new to Android Studio and i have a question. I'm currenly using this method to SetContent

 ImageView img1 = (ImageView)findViewBtId(R.id.Img1);
 ImageView img2 = (ImageView)findViewBtId(R.id.Img2);`

but i wanted to array the img1,img2,img3so i can setcontent them automaticly somthing like this

 ArrayList <ImageView> imgs = new ArrayList <ImageView>();
 imgs.add("img1");
 imgs.add("img2");
 imgs.add("img3");

 for (int i =0;int i < imgs.length();i++)
 { imgs[i] = ...;}

Can I use this or something else? Does Android Studio can't have something like that?

MLong
  • 11
  • 4
  • You can use the `Resources#getIdentifier()` method inside a loop. It will return the numeric ID that you can use in place of an `R.id` with `findViewById()`. For example, `int id = getResources().getIdentifier("img" + (i + 1), "id", getPackageName());`, `imgs.add((ImageView) findViewById(id));`. – Mike M. Nov 18 '19 at 03:41
  • Thanks you so much, that was what I was looking for. – MLong Nov 18 '19 at 03:59
  • No problem. Please do select the "That solved my problem!" option so that this can be marked as resolved. Thanks. Cheers! – Mike M. Nov 18 '19 at 04:10
  • @MikeM. I can't mark your comment as an answer (because it's a comment) so can you put an answer below so i can mark it?Also how can i unmark as duplicate?I was trying to mark your comment and that pop up :D – MLong Nov 21 '19 at 03:14
  • It's cool. I just summarized what the answers on the linked duplicate says. No need to repeat them in another answer here. That's why we mark duplicates; to keep solutions for a given problem in one spot. You did the right thing. Thank you, though. I appreciate the offer. Glad you got it working. Cheers! – Mike M. Nov 21 '19 at 03:18

1 Answers1

0
You can assign dynemically like: 

Here is the XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

And the Actvity File

public class TestActivity extends Activity{

    private String[] id;
    private ImageView[] imageViews = new ImageView[2];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testactivity);

        int temp;
        id = new String[]{"img1", "img2"};

        for(int i=0; i<id.length; i++){
           temp = getResources().getIdentifier(id[i], "id", getPackageName());
           imageViews[i] = (ImageView) findViewById(temp);
        }
    }

Hope you understand and do according your need.
kaushal malvi
  • 72
  • 1
  • 6