skip to Main Content

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>

3

Answers


  1. Chosen as BEST ANSWER

    So I removed "finish()" from all the intent codes and it worked by naming the parent activity in the manifest file


  2. 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

    Login or Signup to reply.
  3. 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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search