动态创建多个ImageView

时间:2016-05-29 17:26:04

标签: java android imageview dynamically-generated

我有这个代码来创建一个ImageView但是当我多次运行这个方法时,之前创建的ImageView会被替换,因为它们具有相同的Id。我怎样才能防止这种情况发生?

以下是方法:

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;
    }

1 个答案:

答案 0 :(得分:1)

为每个imageview对象设置id

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;
    }