user3833308
user3833308

Reputation: 1212

How to programatically add and remove view from Fragment

I want to have two .xml layout files for a Fragment conditionally I want to launch one and change to other on some event, tried searching Javadoc to find relevant methods, any pointers would be helpful

Upvotes: 0

Views: 1713

Answers (2)

Panther
Panther

Reputation: 9408

Try this..

public class FragmentCont extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater,
    ViewGroup container, Bundle savedInstanceState) {

   //Inflate the layout for this fragment
   if(condition1){
    return inflater.inflate(
          R.layout.fragment_one, container, false);
   }else{
    return inflater.inflate(
          R.layout.fragment_two, container, false);
   }


  }
}

Upvotes: 0

Himanshu Agarwal
Himanshu Agarwal

Reputation: 4683

You need to create two classes that extends Fragment class and override onCreateView() method and inflate your layout. ex:

Class FragmentOne.java

   public class FragmentOne extends Fragment {
   @Override
   public View onCreateView(LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {

       //Inflate the layout for this fragment

      return inflater.inflate(
              R.layout.fragment_one, container, false);


      }
    }

Class FragmentTwo.java

public class FragmentTwo extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater,
  ViewGroup container, Bundle savedInstanceState) {

  // Inflate the layout for this fragment

  return inflater.inflate(
          R.layout.fragment_two, container, false);


 }
}

And in your MainActivity.java

    Fragment fr;

         if(view == findViewById(R.id.button2)) {
             fr = new FragmentTwo();

         }else {
             fr = new FragmentOne();
         }

         FragmentManager fm = getFragmentManager();
         FragmentTransaction fragmentTransaction = fm.beginTransaction();
         fragmentTransaction.replace(R.id.fragment_place, fr);
         fragmentTransaction.commit();

Upvotes: 2

Related Questions