Manage toolbar's navigation and back button from fragment in android

前端 未结 8 1981
庸人自扰
庸人自扰 2020-12-02 10:00

All of my fragments are controlled through ActionBarActivity (mainActivity), inside mainActivity a DrawerLayout is implemented and all the child fr

相关标签:
8条回答
  • 2020-12-02 10:39

    First you add the Navigation back button

       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    

    Then, add the Method in your HostActivity.

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==android.R.id.home)
        {
            super.onBackPressed();
            Toast.makeText(this, "OnBAckPressed Works", Toast.LENGTH_SHORT).show();
        }
    
        return super.onOptionsItemSelected(item);
    }
    

    Try this, definitely work.

    0 讨论(0)
  • 2020-12-02 10:42

    You have to manage your back button pressed action on your main Activity because your main Activity is container for your fragment.

    First, add your all fragment to transaction.addToBackStack(null) and now navigation back button call will be going on main activity. I hope following code will help you...

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            }
        return super.onOptionsItemSelected(item);
    }
    

    you can also use

    Fragment fragment =fragmentManager.findFragmentByTag(Constant.TAG); 
    if(fragment!=null) {          
          FragmentTransaction transaction = fragmentManager.beginTransaction();
          transaction.remove(fragment).commit();
    }
    

    And to change the title according to fragment name from fragment you can use the following code:

    activity.getSupportActionBar().setTitle("Keyword Report Detail");
    
    0 讨论(0)
提交回复
热议问题