Menachem Hornbacher
Menachem Hornbacher

Reputation: 2166

LinearLayout not displaying images added programmatically

I am trying to make a line of hearts indicating the number of lives the player currently has. This is my code:

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 (Excerpt):

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

Here is the result:

Only one heart is shown

When they lose a life the number goes down properly and the image goes away after the last life. also logging the layout.getChildCount() gives me 6 (the textview and the 5 added imageView i guess). Can someone please explain why the are not showing on screen.

Thank you in advance.

Upvotes: 0

Views: 249

Answers (1)

FINDarkside
FINDarkside

Reputation: 2435

You are setting the image only to the first ImageView. To be more precise you set it 5 times.

    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

Upvotes: 2

Related Questions