Android - How to get parentActivityName attribute

2019-06-07 22:25发布

问题:

An activity is declared in my manifest like this:

    <activity
        android:name=".TicketingHomeActivity"
        android:label="@string/title_activity_ticketing_home"
        android:parentActivityName=".HomeActivity" />

How can I get the value of android:parentActivityName programmatically?

I need to do this as I have just replaced my ActionBar with a Toolbar, but getSupportActionBar().setDisplayShowHomeEnabled(true) is now showing the Up arrow in an activity even when there is no parentActivityName attribute set in the manifest. Therefore, I would like to detect in my BaseActivity if no parentActivityName has been set, so I can hide the Up arrow accordingly.

NB - This question is not a duplicate of this question as I am specifically asking how to detect the value of the android:parentActivityName attribute programmatically.

回答1:

You can call getParentActivityIntent() on your BaseActivity.

It will return an Intent. Then you can call getComponent() that will return a ComponentName from where you can obtain the android:parentActivityName (classname).

EDIT

Code example:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {

        toolbar.setTitle(getTitle());

        Intent parentActivityIntent = getParentActivityIntent();
        boolean doesParentActivityExist;
        if (parentActivityIntent == null) {
            doesParentActivityExist = false;
        }
        else {
            ComponentName componentName = parentActivityIntent.getComponent();
            doesParentActivityExist = (componentName.getClassName() != null);
        }
        //toolbar.setSubtitle("Has parent: " + doesParentActivityExist);

        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null && doesParentActivityExist) {

            actionBar.setDisplayHomeAsUpEnabled(doesParentActivityExist);
            actionBar.setHomeButtonEnabled(doesParentActivityExist);

            actionBar.setDefaultDisplayHomeAsUpEnabled(doesParentActivityExist);
            actionBar.setDisplayShowHomeEnabled(doesParentActivityExist);

        }
    }


回答2:

Simply if you do not set attribute in manifest then do not use setDisplayShowHomeEnabled() method for that activity.
Otherwise one of the way is You can put Parent Activity Name in putExtra to the parent Activity(Calling Activity) and receive that in child activity(Called Activity)

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
     intent.putExtra("PARENT_ACTIVITY_NAME", "ThisActivityName");
     startActivity(intent);

And then receive in child like

String parentActivityName = intent.getStringExtra("PARENT_ACTIVITY_NAME");

And for this purpose This Answer may also work.