user8637375
user8637375

Reputation: 11

Generate randomly images on ImageView with array

I'm trying create an array then generate a random image on ImageView, but my code has a problem... setBackgroundResource generates an error and the message android studio is Cannot resolve method 'setBackgroundResource(int)' My code is:

@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button btn=(Button)findViewById(R.id.btn); 
    final RelativeLayout background = (RelativeLayout) findViewById(R.id.back); 
    Resources res = getResources(); 
    final TypedArray myImages = res.obtainTypedArray(R.array.myImages); 
    btn.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
            final Random random = new Random(); 
            int randomInt = random.nextInt(myImages.length()); 
            int drawableID = myImages.getResourceId(randomInt, -1); 
            background.setBackgroundResource(drawableID); 
        } 
    }); 
}

Upvotes: 1

Views: 907

Answers (1)

Jon
Jon

Reputation: 1763

Since you're accessing the array in a different context, you should pull the data out of typed array into a list (or an array) and store it as a member variable.

private List<Integer> myImages;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn=(Button)findViewById(R.id.btn);
    final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
    myImages = getResourceList(R.array.myImages);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Random random = new Random();
            int randomInt = random.nextInt(myImages.size());
            int drawableID = myImages.get(randomInt);
            background.setBackgroundResource(drawableID);
        }
    });
}

public List<Integer> getResourceList(int arrayId){
    TypedArray ta = getResources().obtainTypedArray(arrayId);
    int n = ta.length();
    List<Integer> resourceList = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        int id = ta.getResourceId(i, 0);
        resourceList.add(id);
    }
    ta.recycle();

    return resourceList;
}

Upvotes: 1

Related Questions