In my android project, I am dynamically adding forms to my linear layout and then destroying them when I am done with a button. However, When I click the "add button" It infinitely adds more forms although I want only one at a time. How can i chec if my linearLayout "accounts" has been added to the view or if it exists in the view at the time? This is the code to add the view. How can I check to see if the view already exists before I add the view?
public void showForm(String form){
View view;
LayoutInflater inflater
=(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.forms, null);
LinearLayout item = (LinearLayout) view.findViewById(R.id.accounts);
l.addView(item);
}
Option #1: Use boolean accountsAdded=false;
, setting it to true
when needed
Option #2: Use l.findViewById(R.id.accounts)
and see if that returns null
BTW, you will crash if the root widget of R.layout.forms
is not the R.id.accounts
View
, so please add view
, not item
, to l
via addView()
.
You can check from ViewGroup indexOfChild(View view) method if the child is exist or not. it returns a positive integer representing the position of the view in the group, or -1 if the view does not exist in the group
ViewGroup rootLayout = (ViewGroup) getWindow().peekDecorView();
LayoutInflater li = LayoutInflater.from(this);
View myView= li.inflate(R.layout.recorder, null);
if(rootLayout.indexOfChild(myView) == -1)
rootLayout.addView(myView);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With