简体   繁体   中英

Show a Fragment over everything else currently in view, and then remove it on button click

I'm currently trying to make a fragment come into view over everything else in the activity. Then, on a button press, the fragment should disappear and reveal everything that was there previously.

Here is my current attempt:

            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
                    .replace(currentFragment.getId(), fragment);
            transaction.addToBackStack(null);
            transaction.commit();

and on the button press, I do:

            getFragmentManager().popBackStack();

But the issue I'm having it the fragment doesn't totally inflate overtop all the other views, and the button press is not having the desired affect. Any suggestions?

EDIT: It's a bottomNavigationView that's still showing, I'd like to inflate overtop of that.

You can use Dialog fragment like:

public class PopUpDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Context context = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(context);

    builder.setTitle("Your title")
            .setMessage("Your message")
            .setPositiveButton("Button name", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   //Do your stuff here

                   dismiss();
               }
           });
    return builder.create();
}

}

Then you call it from your activity like:

PopUpDialogFragment fragment = new PopUpDialogFragment();
fragment.show(getFragmentManager(), "popUp");

If you want a Fragment with your own custom view then you create one with onCreateView method.

public class PopUpDialogFragment extends DialogFragment {

private Button button;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
           container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.your_layout, 
           container, false);
    button = view.findViewById(R.id.your_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Do your stuff here

            getDialog().dismiss();
        }
    });

    return view;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM