j0ntech
j0ntech

Reputation: 1168

Add Views to LinearLayout programmatically

I have an Activity that displays comments. The comments themselves have a layout, so I can't just use a ListView.

I'm adding the comments with a loop, and the program goes through the whole loop (checked via LogCat), but only adds the first View (comment) to the linearlayout.

My code (in reality the fillComments parameter will be something else than 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);
    }
}

Upvotes: 5

Views: 14670

Answers (2)

Ramesh Solanki
Ramesh Solanki

Reputation: 2926

i think mCommentArea = (LinearLayout) findViewById(R.id.comments_area); this layout orientation is Horizontal so this problems occurs. please if horizontal orientations then please change it to vertical and enjoy

Upvotes: 6

user1169390
user1169390

Reputation: 151

How have you defined the LinearLayout? It could be just a display issue. Check the size and orientation of LinearLayout.

Upvotes: 2

Related Questions