Skip to content

Instantly share code, notes, and snippets.

@gbzarelli
Last active January 29, 2024 02:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbzarelli/036b58ec0f086730c915edf8326fefd8 to your computer and use it in GitHub Desktop.
Save gbzarelli/036b58ec0f086730c915edf8326fefd8 to your computer and use it in GitHub Desktop.
Android - Adicionando onBackPressed com dois clicks no Fragment - Clicking the back button twice to exit in fragment
import android.os.CountDownTimer
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.FragmentActivity
import java.util.concurrent.atomic.AtomicBoolean
fun FragmentActivity.addOnBackPressedCallbackWithInterval(
millisToBack: Long,
firstPressed: () -> Unit
) {
onBackPressedDispatcher.addCallback(
this, ActivityUtils.getOnBackPressedCallbackWithInterval(
this,
millisToBack,
firstPressed
)
)
}
object ActivityUtils {
fun getOnBackPressedCallbackWithInterval(
fragmentActivity: FragmentActivity,
millisToBack: Long,
firstPressed: () -> Unit
) =
object : OnBackPressedCallback(true) {
var pressed = AtomicBoolean(false)
val counter = object : CountDownTimer(millisToBack, millisToBack) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
if (pressed.get()) {
pressed.set(false)
}
}
}
override fun handleOnBackPressed() {
if (pressed.get()) disableAndPressOnBack()
else {
pressed.set(true)
firstPressed()
}
counter.start()
}
private fun disableAndPressOnBack() {
isEnabled = false
fragmentActivity.onBackPressed()
remove()
}
}
}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import br.com.helpdev.R
import br.com.helpdev.lib.helper.activity.addOnBackPressedCallbackWithInterval
class MenuFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_menu, container, false)
}
override fun onAttach(context: Context) {
super.onAttach(context)
configureOnBackPress()
}
private fun configureOnBackPress() {
requireActivity().addOnBackPressedCallbackWithInterval(2000) {
Toast.makeText(
context,
getString(R.string.alert_press_again_to_exit),
Toast.LENGTH_LONG
).show()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment