FragmentPagerAdapter - How to handle Orientation Changes?

╄→гoц情女王★ 提交于 2019-11-27 22:48:49

Yes like you said FragmentManager handles fragments after orientation change so getItem in adapter is not called. But you can override method instantiateItem() which is called even after orientation change and cast Object to Fragment and save it in your array.

 @Override
 public Object instantiateItem(ViewGroup container, int position) {
     DataFragment fragment = (DataFragment) super.instantiateItem(container, position);
     fragments[position] = fragment;
     return fragment;
 }

Could not you just set the android:configChanges flag on your Activity in AndroidManifest.xml to prevent activity to be recreated?

<activity
    android:name="com.example.test.activity.MainActivity"
    android:configChanges="orientation|screenSize|keyboardHidden"/>

also there you can find more possibilities: https://android.jlelse.eu/handling-orientation-changes-in-android-7072958c442a

I had similar problem my working solution: In activity where is an adapter call adapter.notifyDataSetChanged();

override getItemPostion() method in your adapter

@Override
    public int getItemPosition(Object object) {
        MyFragment frag = (MyFragment)object;
        frag.refresh();
        return POSITION_UNCHANGED;
    }

my FragmentStatePagerAdapater (my adapter) contains only one type of fragment, but I am think, that you could use instanceof (for more types of Fragments) and then use cast or every fragment will implement Interface with method refresh()

Then add method refresh() in your Fragment(s) and use this implementation:

public void refresh() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        ViewGroup viewGroup = (ViewGroup) getView();
        viewGroup.removeAllViewsInLayout();
        View view = onCreateView(inflater, viewGroup, null);
        viewGroup.addView(view);

    }

This worked for me. My opinion: The problem has came, when the device change orientation, adapter is destroyed, but the fragments are still in memory and system try to reuse them after orientation change, but the views which are contains in the fragments are destroyed too and fragments needs to be "recreate" (call onCreateView method ). Maybe I am wrong, so please correct me... .

(Sorry for my english )

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!