Nathiel Paulino Nathiel Paulino - 1 month ago 29
Java Question

How to create a back button in ActionBar AppCompatActivity Android Studio

I created a simple

Navigation Drawer Activity
and a
Basic Activity
which I named of
LoginActivity
, so when I select a item from my Drawer i was able to navigate to my LoginActivity but there's no BackButton in my ActionBar, I came from Xamarin Forms and there, depending on navigation type, the back button was visible! So far I have :

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); ................

public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();

if (id == R.id.nav_camera) {
Intent intent = new Intent(this,LoginActivity.class);
startActivity(intent);

Android Studio 2.2.2
compileSdkVersion 24

Answer

Change this code in your onCreate method:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.YOUR_NAVIGATION_ICON); //This is the line to add

Furthermore, you can determine what clicking this icon does by:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                //Whatever your require the navigation to do
                return true;

        }
    }