Working with BACK buttons on the Navigation Bar (native smartphone) and Action Bar (added via Java)

0

I'm asking this question / answer to help anyone who might have had / have any questions regarding the BACK buttons that are extremely useful in our applications. I'll use 1 and 2 to differentiate Action Bar and Navigation Bar (2)

Thank you very much to the users of Stack who helped me to find this solution that were: Jean Felipe D. Silva and Regmoraes     

asked by anonymous 18.04.2016 / 20:54

1 answer

5

1. Back - Action Bar

  • Within method onCreate(){ add the following lines:

    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Mostrar o botão
    getSupportActionBar().setHomeButtonEnabled(true);      //Ativar o botão
    getSupportActionBar().setTitle("Seu titulo aqui");     //Titulo para ser exibido na sua Action Bar em frente à seta
    
  • Out of method oncreate(){} add:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { //Botão adicional na ToolBar
    switch (item.getItemId()) {
        case android.R.id.home:  //ID do seu botão (gerado automaticamente pelo android, usando como está, deve funcionar
            startActivity(new Intent(this, SuaActivity.class));  //O efeito ao ser pressionado do botão (no caso abre a activity)
            finishAffinity();  //Método para matar a activity e não deixa-lá indexada na pilhagem
            break;
        default:break;
    }
    return true;
    }
    

Everything is ready, your Action Bar button is working!

2. Back - Navigation Bar

  • Out of method onCreate(){}

    @Override
    public void onBackPressed(){ //Botão BACK padrão do android
    startActivity(new Intent(this, MainActivity.class)); //O efeito ao ser pressionado do botão (no caso abre a activity)
    finishAffinity(); //Método para matar a activity e não deixa-lá indexada na pilhagem
    return;
    }
    

Everything should be working perfectly now

    
18.04.2016 / 20:54