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

5
我有一个展示评论的Activity。这些评论本身有一个布局,所以我不能只使用ListView。
我使用循环添加了评论,程序通过整个循环(通过LogCat检查),但只向线性布局添加了第一个视图(评论)。
我的代码(实际上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);
    }
}

如果 R.id.comments_area 的方向是垂直的且宽度为 fill_parent,那么这种情况也会发生吗?并且日志(“Comment adder”)会显示多次吗? - louiscoquio
请问您能否展示一下布局:comment_row_layout.xml?我猜测它是水平方向的。 - Maher Abuthraa
2个回答

6
我认为这个问题出现的原因是布局方向是横向的。如果您将其更改为纵向,就不会有这个问题了。请尝试修改下面这行代码: mCommentArea = (LinearLayout) findViewById(R.id.comments_area); 使之符合您需要的方向,并享受它带来的便利。

2

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


你说得对,我忘记在我的LinearLayout中添加android:orientation="vertical"这一行了。 - j0ntech

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接