Yudi Moszkowski
Yudi Moszkowski

Reputation: 80

Dynamically create multiple ImageViews

I have this code to create an ImageView but when I run this method multiple times, the previous ImageView created is replaces because they have the same Id's. How can I prevent this from happening?

Here is the method:

public ImageView getCardView(String Card){

        ImageView imageView = new ImageView(this);

        switch(Card){
            case "joker-one":
                imageView.setImageResource(R.drawable.jokerone);
                imageView.setMaxHeight(20);
                imageView.setMaxWidth(10);
            break;

            default:
                imageView.setImageResource(R.drawable.kingdiamonds);
                imageView.setMaxHeight(20);
                imageView.setMaxWidth(10);
            break;
        }

        return imageView;
    }

Upvotes: 0

Views: 102

Answers (1)

Muhammad Waleed
Muhammad Waleed

Reputation: 2601

Set id for each imageview object

public ImageView getCardView(String Card){

        ImageView imageView = new ImageView(this);

        switch(Card){
            case "joker-one": 
                imageView.setImageResource(R.drawable.jokerone);
                imageView.setMaxHeight(20);
                imageView.setMaxWidth(10);
                imageView.setId(1);

            break; 

            default: 
                imageView.setImageResource(R.drawable.kingdiamonds);
                imageView.setMaxHeight(20);
                imageView.setMaxWidth(10);
                imageView.setId(2);
            break; 
        } 

        return imageView;
    } 

Upvotes: 1

Related Questions