Archie.bpgc
Archie.bpgc

Reputation: 24012

Android: Adding multiple Views to a Linear Layout dynamically

I checked the solution here:

Adding multiple views of the same type

Its given that, create a new View everytime you add it instead of changing only 1 view.

But i am doing this:

for (int i = 0; i < 10; i++) {

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(
                    CommentsActivity.LAYOUT_INFLATER_SERVICE);
View cv = vi.inflate(R.layout.item, null);

TextView textView1 = (TextView) cv.findViewById(R.id.tv1);
textView1.setText("-" + i);
TextView textView2 = (TextView) cv.findViewById(R.id.tv2);
textView2.setText("--" + i);
LinearLayout insertPoint = (LinearLayout) findViewById(R.id.layout);
insertPoint.addView(cv, 0, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}

so its like creating a new inflater and view for every i. But i am only getting the last item.

ie.., only 1 inflatedView with tv1 as -9 and tv2 as --9

seems like everytime i go into the for loop, the old view is being replaced by the new view. How to add all the 10 views??

ThankYou

Upvotes: 1

Views: 5368

Answers (1)

Niko Adrianus Yuwono
Niko Adrianus Yuwono

Reputation: 11122

usually I use this

private void renewDetail(){
        llDetail.removeAllViews();
        for (int i = 0; i < 10; i++) {
            llDetail.addView(new ChildDetailNotePieDiagram(context, "Name", 1000, 10));
        }
    }

the logic is first I clear all view from the parent layout and then add view to the parent layout.

where llDetail is a linear layout and I create a linear layout class ChildDetailNotePieDiagram and add it to the linear layout so basically it's a different solution from what you use now but I think you can try my solution if you want :) feel free to ask any question about this in the comment

Upvotes: 3

Related Questions