Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
   }
like image 861
Dnaso Avatar asked Dec 06 '13 20:12

Dnaso


2 Answers

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

like image 69
CommonsWare Avatar answered Oct 17 '22 14:10

CommonsWare


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);
like image 32
Muhammad Aamir Ali Avatar answered Oct 17 '22 15:10

Muhammad Aamir Ali