动态地将组件添加到CardView内的LinearLayout中,仅添加第一个

时间:2019-04-11 07:52:28

标签: android android-custom-view

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

有人知道我在做什么不好吗?

1 个答案:

答案 0 :(得分:0)

似乎您尚未在动态布局上设置方向。

只需添加rl2.setOrientation(),您的代码即可正常运行。

  

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

谢谢