Skip to content

Commit

Permalink
Replace deprecated onBackPressed with onBackPressedDispatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
Xcreen committed Dec 16, 2024
1 parent d35852c commit 3ffc017
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions app/src/main/java/net/xcreen/restsms/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
Expand Down Expand Up @@ -48,7 +49,7 @@ class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelecte
val navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)

//Dont replace Fragment, on orientation-change
//Don't replace Fragment, on orientation-change
if (savedInstanceState == null) {
//Set Home Fragment
val fragmentTransaction = supportFragmentManager.beginTransaction()
Expand All @@ -59,6 +60,17 @@ class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelecte
ex.printStackTrace()
}
}

onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
})
}

override fun onCreateOptionsMenu(optionsMenu: Menu): Boolean {
Expand All @@ -67,15 +79,6 @@ class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelecte
return true
}

override fun onBackPressed() {
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
onBackPressedDispatcher.onBackPressed()
}
}

override fun onNavigationItemSelected(item: MenuItem): Boolean {
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
//Remove all Option-Menu-Items
Expand Down

0 comments on commit 3ffc017

Please sign in to comment.