Why is the up button present without setDisplayHom

2019-03-25 05:07发布

According to Google's document, getActionBar().setDisplayHomeAsUpEnabled(true) is needed to show the up button. I created a bare-bone activity using the wizard in Eclipse and specified its parent activity. I could not find any getActionBar().setDisplayHomeAsUpEnabled(true) in the automatically generated code, but the up button is present when this activity is started and it works as expected. Could anyone shed some light on this?

public class FooActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foo);

            //more code...    
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            //more code...  
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            //more code...  
            return rootView;
        }
    }

}

2条回答
做自己的国王
2楼-- · 2019-03-25 05:31

I described all possible combinations below and their outcomes:

  1. You have both android:parentActivityName=".MyActivityand this getActionBar().setDisplayHomeAsUpEnabled(true); - back button appears and it works;
  2. You only have this android:parentActivityName=".MyActivity - back button appears and it works, the same as above;
  3. You only have this getActionBar().setDisplayHomeAsUpEnabled(true);, - back button appears but clicking on it doesn't go anywhere;
  4. You have set the parameter to false in this getActionBar().setDisplayHomeAsUpEnabled(false);, even though you have this android:parentActivityName=".MyActivity in the manifest, the back button doesn't show up.

That's how this works my friend.

查看更多
迷人小祖宗
3楼-- · 2019-03-25 05:47

When you specify a parentActivityName in your AndroidManifest, Acitivty will check for that and automatically enable the "up" affordance if it's present.

查看更多
登录 后发表回答