Question

In my activity i'm using onConfigurationChanged when orientation is changing :

@Override
 public void onConfigurationChanged(Configuration newConfig)
 {
     super.onConfigurationChanged(newConfig);

     if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
     {
         Log.e(TAG,"onConfigurationChanged LANDSCAPE");
     }
     else
     {
         Log.e(TAG,"onConfigurationChanged PORTRAIT");
     }
 }

I want to refresh my fragment view, so ask the code to call onCreateView. Is there any way to achieve that ?

Was it helpful?

Solution

The solution is :

In my abstract fragment class (extends from Fragment)

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    final View view = getView();

    ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {


        @Override
        public void onGlobalLayout() {
            LayoutInflater inflater =  (LayoutInflater) ARApplication.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            populateViewForOrientation(inflater, (ViewGroup) getView());

            // Avoid infinite loop
            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        }
    });
}

protected abstract void populateViewForOrientation(LayoutInflater inflater, ViewGroup view);

Every instance of MyFragment have to implement the populateViewForOrientation() method :

protected void populateViewForOrientation(LayoutInflater inflater, ViewGroup viewGroup) {
    viewGroup.removeAllViewsInLayout();
    View subview = inflater.inflate(R.layout.welcome, viewGroup);
    // do all the stuff
}

OTHER TIPS

Fragment has it's own onConfigurationChanged callback, so in Fragment do

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final ViewGroup root = (ViewGroup) inflater.inflate(R.layout.root_layout, null);
    initView(inflater, view);
    return view;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    final View view = getView();
    if (view != null) {
        initView(getActivity().getLayoutInflater(), (ViewGroup) view.findViewById(R.id.container));
    }
}

private void initView(final LayoutInflater inflater, final ViewGroup parent) {
    parent.removeAllViews();
    final View subRoot = inflater.inflate(R.layout.your_layout, null);
    parent.add(subRoot);
    //do all the stuff
}

Where the root_layout is

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top