0

I want to create a layout (see class RosterPlayerView below) that comprises an image with text below it and then instantiate that view multiple times in a relative layout. I used relative layout instead of linear as the layout will become more complex.

When I first ran the code below (but without the setId calls) the text appeared above the image. Thanks to this stack overflow article I discovered that relative layout needs unique widget ids to work. But when I added the setId() calls the text view is not displayed at all.

What am I doing wrong?

public class RosterPlayerView extends RelativeLayout {

    ImageView imageView;
    TextView textView;
    static int layoutId = 100;

    public RosterPlayerView(Context context, int playerId, Drawable photo) {
        super(context);
        imageView = new ImageView(context);
        textView = new TextView(context);
        addView(imageView, new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        imageView.setId(layoutId++);
        RelativeLayout.LayoutParams timeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        timeLayoutParams.addRule(RelativeLayout.BELOW, imageView.getId());
        addView(textView, timeLayoutParams);        
        imageView.setImageDrawable(photo);
        textView.setId(layoutId++);
        textView.setText("0:00");
    }
}
Community
  • 1
  • 1
whenrybruce
  • 91
  • 1
  • 7

2 Answers2

0

Try to set the Id of you imageView before adding it to the layout.

You can also create a LinearLayout with the imageView and textView inside before adding it to the RelativeLayout

JWqvist
  • 717
  • 6
  • 15
0

a LinearLayout would be an awful lot simpler for what you are trying to do. So would inflating an XML layout, for that matter.

Philip Sheard
  • 5,789
  • 5
  • 27
  • 42
  • Philip - you're right linear layout is much simpler. I went with relative layout as I'd like to influence position of textView and add more widgets to layout. Thanks for your help. – whenrybruce Oct 04 '13 at 16:32