When I'm pressing the back button on phone or the support action bar, it's exiting the application. How can I fix it to return to the main activity In login code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
supportActionBar?.setDisplayShowHomeEnabled(true)
.... }
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
NavUtils.navigateUpFromSameTask(this)
return true
}
}
return super.onOptionsItemSelected(item)
}
And in the manifest file:
<activity
android:name=".LoginActivity"
android:label="Login"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.food_bank.MainActivity"/>
</activity>
CodePudding user response:
what works for me:
MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener{
startActivity(Intent(this, LoginActivity::class.java))
}
}
}
LoginActivity:
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
// no onOptionsSelected here
}
Manifest:
(...)
<activity
android:name="LoginActivity"
android:exported="false"
android:label="@string/title_activity_login"
android:parentActivityName=".MainActivity"/>
(...)
I guess switching from two times supportActionBar?.setDisplayShowHomeEnabled(true)
to supportActionBar?.setDisplayHomeAsUpEnabled(true)
has something to do with it
CodePudding user response:
Change your onOptionsItemSelected
like this
android.R.id.home -> {
onBackPressed()
return true
}
and override onBackPressed
method on your activity like this
override fun onBackPressed() {
super.onBackPressed()
NavUtils.navigateUpFromSameTask(this)
}