Question

I have a few Actiobar with 5 tabs each with a fragment. In 3 of this fragments I want to show a Dialog so I've created a new class:

 public static class MyDialogFragment extends DialogFragment {
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        static MyDialogFragment newInstance() {
            return new MyDialogFragment();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            int style = DialogFragment.STYLE_NORMAL;
            int theme =  android.R.style.Theme_Holo_Dialog;

            setStyle(style, theme);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.fragment_dialog, container, false);
            View tv = v.findViewById(R.id.textV);
            ((TextView)tv).setText("Dialog using style Normal - Theme AlertDialog - NoActionBar");


            return v;
        }
    }

In every onCreate method of this 3 fragments I'm trying to show the Dialog by using this method:

private void showPopup()
{
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment prev = getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    DialogFragment newFragment = MyDialogFragment.newInstance();
    newFragment.show(ft, "dialog");

}

Now the problem is that this dialog is displayed on tabs that should not.

For example I want tabs 1 3 and 5 to display the Dialog - and sometimes it displays it - but sometimes when I tap the tab 2 this dialog appears and if I tap 3 the Dialog is not showed. What could be the problem and how should I fix it? Thanks

Was it helpful?

Solution

Have you try to move your showPopup() call in onCreateView() or in onActivityCreated() methods, instead of in onCreate() one ?

EDIT: According to comments below, the problem is linked to the use of a ViewPager, which prepare some next Fragments to be viewed, and then call onCreate() methods.

OTHER TIPS

So I've found a solution - in every fragment I override a method called setMenuVisibility - and test if the the fragment is visible. If it is - I call my method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top