动态添加组件到 CardView 内的 LinearLayout,只有第一个被添加

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

我正在向 CardView 内的 LinearLayout 添加一些自定义组件。第一个组件完美添加,但下一个组件未绘制。组件的 ArrayList 有各种元素(在我的例子中有两个):

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

在这里,scoreTeams ArrayList 有两个插槽,我测试过),但只显示第一个。 ll 是一个 LinearLayout。

这是一个 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)]));
  }
}

有人知道我做错了什么吗?

您似乎没有在动态布局上设置方向。

只需添加 rl2.setOrientation(),您的代码就可以正常工作。

Possible values should be LinearLayout.VERTICAL or LinearLayout.HORIZONTAL

谢谢