Reputation: 473
I am creating an application where I need to dynamically create elements. I'm using the following code in the onCreate () method.
TextView product = new TextView (this);
product.setText ("" + pName + "");
//Add TextView to LinearLayout
ll.addView (product);
Works fine, the problem is when I turn the phone, the items appear duplicated. What am I doing wrong?
Upvotes: 0
Views: 66
Reputation: 8826
When you rotate your phone, it destroys the activity and creates again but it saves everything to resume, onCreate()
method you create textviews again although they are already in the view.
You should check them before create.
You can do that by checking savedInstanceState
, if it's not null, that means it's being recreated again.
if (savedInstanceState == null){
// create your textviews
}
Upvotes: 2
Reputation: 606
You are creating the TextView
programmatically and when you turn the phone, you don't eliminate the object from your layout so you are adding elements in your layout everytime you create the activity. You can control it in your onDestroy()
method.
I hope it helps.
Upvotes: 1