Intended usage of Up navigation

前端 未结 1 1334
小鲜肉
小鲜肉 2021-01-15 05:38

My app is Activity based and has several levels, i.e. ActivityA has actions to start ActivityB, which in turn starts ActivityC. Pressing \'back\' from ActivityC returns to A

相关标签:
1条回答
  • 2021-01-15 06:26

    1) No, you are not trying to misuse the ActionBar here. If you are going from A -> B -> C then pressing Up from C should take you to B and NOT A. This is mentioned here as

    "The Up button is used to navigate within an app based on the hierarchical relationships between screens. For instance, if screen A displays a list of items, and selecting an item leads to screen B (which presents that item in more detail), then screen B should offer an Up button that returns to screen A."

    2)Your implementation is not working as intended because you forgot to do the following as mentioned here:

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_displaymessage);
    
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            // If your minSdkVersion is 11 or higher, instead use:
            // getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    

    I however do not recommend that you use the above technique to handle your Up Navigation as the above method will not work for ICS and below. The reason it won't work is because NavUtils behaves differently for Pre JellyBean and Post JellyBean as explained in this SO.

    A better way is to do this is to handle the Up action manually in the Child Activity:

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                startActivity(new Intent(this, ParentActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                              Intent.FLAG_ACTIVITY_SINGLE_TOP));
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    

    And best part of this manual approach is that it works for ALL Api Levels.

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