LinearLayout不显示以编程方式添加的图像

时间:2015-04-07 20:52:35

标签: java android arraylist imageview android-linearlayout

我正在试图表明玩家目前拥有的生命数量。这是我的代码:

LifeGraphics.java

public class LifeGraphics {
    public static ArrayList<ImageView> getLiast(Context context){
        ImageView life1 = new ImageView(context);
        life1.setImageResource(R.mipmap.heart);
        ImageView life2 = new ImageView(context);
        life1.setImageResource(R.mipmap.heart);
        ImageView life3 = new ImageView(context);
        life1.setImageResource(R.mipmap.heart);
        ImageView life4 = new ImageView(context);
        life1.setImageResource(R.mipmap.heart);
        ImageView life5 = new ImageView(context);
        life1.setImageResource(R.mipmap.heart);
        ImageView[] inRetrunList = new ImageView[] {life1, life2, life3, life4, life5};
        ArrayList<ImageView> returnList = new ArrayList<>();
        returnList.addAll(Arrays.asList(inRetrunList));
        return returnList;
    }
}

GameActivity.java(摘录):

ArrayList<ImageView> livesGraphicsList = LifeGraphics.getLiast(getApplicationContext());
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout);
for(int i = 0; i < lives; i++){
    layout.addView(livesGraphicsList.get(i), (i + 1));
}

结果如下:

Only one heart is shown

当他们失去生命时,数字会正常下降并且在最后一次生命之后图像会消失。还记录了layout.getChildCount()给了我6(textview和5添加了imageView我猜)。有人可以解释为什么没有在屏幕上显示。

提前谢谢。

1 个答案:

答案 0 :(得分:2)

您只将图像设置为第一个ImageView。更确切地说,你设置了5次。

    ImageView life1 = new ImageView(context);
    life1.setImageResource(R.mipmap.heart);
    ImageView life2 = new ImageView(context);
    life1.setImageResource(R.mipmap.heart); //Should be life2
    ImageView life3 = new ImageView(context);
    life1.setImageResource(R.mipmap.heart);//Should be life3
    ImageView life4 = new ImageView(context);
    life1.setImageResource(R.mipmap.heart);//Should be life4
    ImageView life5 = new ImageView(context);
    life1.setImageResource(R.mipmap.heart);//Should be life5