Dnaso
Dnaso

Reputation: 1365

check to see if a view exists from a layout inflater befor adding another one

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);
   }

Upvotes: 7

Views: 19682

Answers (2)

Muhammad Aamir Ali
Muhammad Aamir Ali

Reputation: 21117

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);

Upvotes: 4

CommonsWare
CommonsWare

Reputation: 1007658

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().

Upvotes: 18

Related Questions