Search code examples
androidkotlinandroid-fragmentsscreenshot

Prevent screenshot in a single fragment android


I have an activity that contains some fragments in it, and I want to prevent screenshot in a single fragment only. But when I apply these codes to Fragment A

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        activity?.window!!.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
        super.onViewCreated(view, savedInstanceState)

    }

the other fragments can't take screenshot too. Can we prevent screenshot only in one fragment ?


Solution

  • You can clearFlag once this fragment is no longer visible . i think this should work ..

     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
    }