以编程方式将视图添加到LinearLayout

时间:2012-01-26 10:38:27

标签: android android-linearlayout

我有一个显示评论的活动。注释本身有一个布局,所以我不能只使用ListView。

我用循环添加注释,程序遍历整个循环(通过LogCat检查),但只将第一个View(注释)添加到linearlayout。

我的代码(实际上fillComments参数不是String []):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.comment_layout);
    String[] comments = {"kommentaar 1", "kommentaar 2", "kommentaar 3"};
    mTitle = (TextView) findViewById(R.id.comments_title);
    mTextArea = (EditText) findViewById(R.id.comment_editor);
    mAddButton = (Button) findViewById(R.id.add_comment);
    mCommentArea = (LinearLayout) findViewById(R.id.comments_area);

    mTitle.setText(getIntent().getStringExtra("name"));
    fillComments(comments);
}

private void fillComments(String[] comments) {
    View comment;
    TextView commentator;
    TextView commentDate;
    TextView commentText;
    LayoutInflater inflater = getLayoutInflater();

    for (String s : comments) {
        Log.d("Comment adder", "Adding comment " + s);
        comment = inflater.inflate(R.layout.comment_row_layout, null);
        commentator = (TextView) comment.findViewById(R.id.commentator);
        commentDate = (TextView) comment.findViewById(R.id.comment_date);
        commentText = (TextView) comment.findViewById(R.id.comment_text);
        commentator.setText("Test commentator");
        commentDate.setText("12-12-2012");
        commentText.setText(s);
        mCommentArea.addView(comment);
    }
}

2 个答案:

答案 0 :(得分:6)

我认为 mCommentArea = (LinearLayout) findViewById(R.id.comments_area); 此布局方向为水平,因此会出现此问题。如果是水平方向,请将其改为垂直方向并享受

答案 1 :(得分:2)

您是如何定义LinearLayout的?这可能只是一个显示问题。 检查LinearLayout的大小和方向。

相关问题