mirror of
https://github.com/Takiiiiiiii/strato.git
synced 2025-07-17 08:46:39 +00:00
Change the way onBackPressedCallback is handled
This commit is contained in:
@ -11,6 +11,7 @@ import android.net.Uri
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.provider.DocumentsContract
|
import android.provider.DocumentsContract
|
||||||
import android.view.View
|
import android.view.View
|
||||||
|
import android.view.inputmethod.InputMethodManager
|
||||||
import androidx.activity.OnBackPressedCallback
|
import androidx.activity.OnBackPressedCallback
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
@ -276,21 +277,30 @@ class MainActivity : AppCompatActivity() {
|
|||||||
adapter.setItems(items)
|
adapter.setItems(items)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val onBackPressedCallback = object : OnBackPressedCallback(true) {
|
||||||
|
override fun handleOnBackPressed() {
|
||||||
|
binding.searchBar.apply {
|
||||||
|
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
|
||||||
|
if (!inputMethodManager.hideSoftInputFromWindow(windowToken, 0)) {
|
||||||
|
text = ""
|
||||||
|
clearFocus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
isEnabled = binding.searchBar.hasFocus() || binding.searchBar.text.isNotEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onStart() {
|
override fun onStart() {
|
||||||
super.onStart()
|
super.onStart()
|
||||||
|
|
||||||
onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
|
binding.searchBar.addTextChangedListener { text ->
|
||||||
override fun handleOnBackPressed() {
|
if (!onBackPressedCallback.isEnabled && !text.isNullOrEmpty()) {
|
||||||
binding.searchBar.apply {
|
onBackPressedCallback.isEnabled = true
|
||||||
if (hasFocus() && text.isNotEmpty()) {
|
|
||||||
text = ""
|
|
||||||
clearFocus()
|
|
||||||
} else {
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
|
||||||
|
onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
|
||||||
|
onBackPressedCallback.isEnabled = binding.searchBar.hasFocus() || binding.searchBar.text.isNotEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
|
Reference in New Issue
Block a user