Error DialogFragment starting in multiple fragments

locho30 :

I currently got a ViewPager that has 3 tabs. Each tab is a fragment. I made a custom dialogFragment to login. I want that logindialog to open only when i go on my 3rd tab. In my onCreateView, i created a new object of my logindialog and show. My problem is, whenever i switch from my 1st tab to 2nd, the dialog also appears and i don't want that.

This is my viewpager adapter

    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return frag1;
            case 1:
                return frag2;
            case 2:
                return frag3;
            default:
                return null;
        }
    }

My 3rd Frag

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_tab_annonce, container, false);

        DialogFragment loginDialog = new DialogFragment();
        loginDialog .show(getActivity().getSupportFragmentManager(), "customLogin");

        return root;
    }
Ben P. :

ViewPager will create and retain "offscreen" pages as a performance optimization (with one offscreen page in either direction by default). What this means in practice is that when you are on Page 1, Page 2 has already been created off-screen. When you switch from Page 1 to Page 2, now Page 3 is created off-screen (and Page 1 is retained in case you want to switch back to it).

That means that onCreateView() is simply not the right place to show the error message.

You could perhaps create your own subclass of ViewPager.SimpleOnPageChangeListener and override onPageSelected() to show the dialog.

ViewPager.OnPageChangeListener listener = new ViewPager.SimpleOnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        if (position == 2) {
            // show dialog
        }
    }
};

viewPager.addOnPageChangeListener(listener);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=319204&siteId=1