Android - Back button in the title bar

前端 未结 26 2066
南方客
南方客 2020-12-04 07:02

In many apps (Calendar, Drive, Play Store) when you tap a button and enter a new activity, the icon in the title bar turns into a back button, but for the app I am making, i

相关标签:
26条回答
  • 2020-12-04 07:38

    If you are using the new support library for 5.1 in android studio, you can instead use this on your AppCompatActivity

     ActionBar actionBar = getSupportActionBar();
     actionBar.setHomeButtonEnabled(true);
     actionBar.setDisplayHomeAsUpEnabled(true);
     actionBar.setHomeAsUpIndicator(R.mipmap.ic_arrow_back_white_24dp);
     actionBar.setDisplayShowHomeEnabled(true);
    

    cheers.

    0 讨论(0)
  • 2020-12-04 07:39

    I saw so much complexes answer, so this is my code. Working here. You can achieve this in two ways.

    1) Stardard android compatiblity

    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.core.app.NavUtils;
    
    import android.view.MenuItem;
    import android.view.View;
    
    public class EditDiscoveryActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_edit_discovery);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            /*toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });*/
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
    
        @Override
        public boolean onSupportNavigateUp() {
            onBackPressed();
            return true;
        }
    
    }
    

    2) Use a custom icon

    If you want to use code in comments you just have to add this file in drawable, called ic_arrow_white_24dp.xml

    <vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
        <path
            android:fillColor="#ffffff"
            android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
        </vector>
    

    With this code.

    toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    

    Hope it will helps some people here !

    0 讨论(0)
提交回复
热议问题