How to disable screen capture in Android fragment?

Performing your disableScreenCapture() call in onResume, onCreateView or onActivityAttached in your Fragment should all work - they did for me. Performing that call in onActivityCreated might not work as I believe that hook is only called when the Activity is being re-created, after it's destroyed. However, I didn't try that one.

If performing that call in onCreateView isn't working for you, are you 100% certain that your Fragment is actually being added to the Activity?

For a DialogFragment it's slightly different:

getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
        WindowManager.LayoutParams.FLAG_SECURE);

A DialogFragment isn't a Dialog itself, but instead holds a reference to one and shows/dismisses it when the fragment is added and removed. Dialogs have their own Windows and must have the flag set individually.


The below code worked for me.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    getActivity().getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
    Window window = getActivity().getWindow();
    WindowManager wm = getActivity().getWindowManager();
    wm.removeViewImmediate(window.getDecorView());
    wm.addView(window.getDecorView(), window.getAttributes());

}