在CardView中动态添加组件到LinearLayout,只添加第一个

问题描述 投票:0回答:1

我正在向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)]));
  }
}

谁知道我做得不好?

android android-custom-view
1个回答
0
投票

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

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

可能的值应为LinearLayout.VERTICAL或LinearLayout.HORIZONTAL

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.