Fustigador
Fustigador

Reputation: 6469

Dynamically adding components to LinearLayout inside CardView, only first is added

I am adding some custom components to a LinearLayout inside a CardView. The first component is added perfectly, but the next aren't drawn. The ArrayList of components has various elements (in my example, there are two):

    LinearLayout.LayoutParams rlParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    rlParams.setMargins(10,10,10,20);
    CardView cv2=new CardView(StatisticsActivity.this);
    cv2.setElevation(3);
    cv2.setUseCompatPadding(true);
    LinearLayout rl2=new LinearLayout(StatisticsActivity.this);
    cv2.addView(rl2,rlParams);
    for(int i=0;i<scoreTeams.size();i++){
        TeamScoreComponent teamScoreComponent=new TeamScoreComponent(StatisticsActivity.this,scoreTeams.get(i).getTeam(),scoreTeams.get(i).getScore());
        rl2.addView(teamScoreComponent);
    }
    ll.addView(cv2);

Here, the scoreTeams ArrayList have two slots I have tested it), but only first is shown. ll is a LinearLayout.

This is a TeamScoreComponent:

public class TeamScoreComponent extends RelativeLayout {

private TextView teamTV;
private TextView scoreTV;
private int score;
private String team;
private Context ctx;
private String[] colores;

public TeamScoreComponent(Context context,String team, int score) {
    super(context);
    this.score=score;
    this.team=team;
    this.ctx=context;
    inicializar();
}

private void inicializar() {
    String infService = Context.LAYOUT_INFLATER_SERVICE;
    LayoutInflater li =
            (LayoutInflater)getContext().getSystemService(infService);
    li.inflate(R.layout.team_score_layout, this, true);
    scoreTV=findViewById(R.id.score);
    teamTV=findViewById(R.id.teamname);
    scoreTV.setText(String.valueOf(score));
    teamTV.setText(team);
    teamTV.setBackgroundColor(ctx.getColor(R.color.gris));
    colores=ctx.getResources().getStringArray(R.array.colores);
    setRandomBackgroundColor();
}

private void setRandomBackgroundColor(){
    Random rnd = new Random();
    scoreTV.setBackgroundColor(Color.parseColor(colores[rnd.nextInt(colores.length)]));
  }
}

Anyone know what I am doing bad?

Upvotes: 0

Views: 90

Answers (1)

Ajay Mehta
Ajay Mehta

Reputation: 853

Seems you have not set Orientation on your dynamic layout.

Just add rl2.setOrientation() and your code will work fine.

Possible values should be LinearLayout.VERTICAL or LinearLayout.HORIZONTAL

Thank you

Upvotes: 1

Related Questions