Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set new layout in fragment

Tags:

I'm trying to change the layout of a fragment during runtime under a particular condition.

The initial layout in inflated within the onCreateView():

@Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         return inflater.inflate(R.layout.cancel_video, null);     } 

Then sometime later within the fragment code I would like to replace the initial layout with some other layout.

I've tried a few things so far; this is the latest that I have:

private void Something(){     if(checkLicenseStatus(licenseStatus, statusMessage)){                 View vv = View.inflate(getActivity(), R.layout.play_video, null);                 //more code     } } 

How can I accomplish this?

like image 408
Dacto Avatar asked Aug 31 '12 21:08

Dacto


2 Answers

You cannot replace the fragment's layout once it is inflated. If you need conditional layouts, then you either have to redesign your layout and break it down into even smaller elemens like Fragments. Alternatively you can group all the layout elements into sub containers (like LinearLayout), then wrap them all in RelativeLayout, position them so they overlay each other and then toggle the visibility of these LinearLayouts with setVisibility() when and as needed.

like image 196
Marcin Orlowski Avatar answered Sep 22 '22 07:09

Marcin Orlowski


Yes, I have done this in following way. When I need to set a new layout(xml), the following code snippet should be executed.

  private View mainView;    @Override   public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState){     super.onCreateView(inflater, containerObject, savedInstanceState);          mainView = inflater.inflate(R.layout.mylayout, null);         return mainView;   }    private void setViewLayout(int id){     LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);     mainView = inflater.inflate(id, null);     ViewGroup rootView = (ViewGroup) getView();     rootView.removeAllViews();     rootView.addView(mainView);   } 

Whenever I need to change the layout I just call the following method

    setViewLayout(R.id.new_layout);  
like image 22
Ujjal Suttra Dhar Avatar answered Sep 23 '22 07:09

Ujjal Suttra Dhar