ban-geoengineering ban-geoengineering - 5 months ago 22
Android Question

Android - How to get parentActivityName attribute value programmatically?

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.

Answer

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);

        }
    }