Android - Back button in the title bar

前端 未结 26 2357
南方客
南方客 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: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

    
        
        
    

    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 !

提交回复
热议问题