0

enter image description here

Hi.

I have tabbed activity, i have 10 fragment in my project and i added "Add Button" button to fragment 1.When i clicked this button, new button has created in linear layout.İts ok, but i have a problem after this.for example, if i go to different tab, my button will be erased.Why this is happening? How can i solve this problem?

Thanks :)

My "Add Button" code ;

public void AddButton(View page){    
       LinearLayout Lay = (LinearLayout) findViewById(R.id.mylayout);    
       Button but = new Button(getApplicationContext());
       but.setText("" + myVec2.size());
       myVec2.add(but);
       mylayout.addView(but);      
   }
metomero
  • 63
  • 1
  • 11

3 Answers3

0

You need a list with buttons on your Fragment and on your onCreateView if that list isn't empty to recreate those buttons.

gmetax
  • 3,853
  • 2
  • 31
  • 45
0

you need to save the buttons onPause() and recreating in onResume()

0
  1. Save the number of buttons in a variable and put it in OnSaveInstanceState.
  2. Restore it in onCreateView in numButtons variable.
  3. If the variable is > 0, add the buttons in your view.
  4. In your button OnClick, do numButton ++ whenever add button is pressed.

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
    
            if (savedInstanceState != null) {
               numButtons = savedInstanceState.getInt(Statics.NUMBER_BUTTONS);
            } else {
               numButtons = 0;
            }
    
           if (numButtons > 0)
              for (int i = 0; i < numButtons; i++) {
           / ** Your Add Button Code ** /
           }
       }
    
       @Override
       public void onSaveInstanceState(Bundle outState) {
           outState.putInt(Statics.NUMBER_BUTTONS, numButtons);
           super.onSaveInstanceState(outState);
       }
    
Aman Arora
  • 134
  • 7