Android - Back button in the title bar

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

    After a quality time I have found, theme option is the main problem in my code And following is the proper way to show the toolbar for me

    In AndroidManifest file first you have to change your theme style

    Theme.AppCompat.Light.DarkActionBar
    to 
    Theme.AppCompat.Light.NoActionBar
    

    then at your activity xml you need to call your own Toolbar like

    
    

    And then this toolbar should be called in your Java file by

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

    And for toolbar showing U should check the null to avoid NullPointerException

    if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    

    For Home activity back add this

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId()==android.R.id.home) {
                finish();
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    

    OR for your desired activity back

    public boolean onOptionsItemSelected(MenuItem item){
        Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);
        startActivityForResult(myIntent, 0);
        return true;
    }
    

提交回复
热议问题