20

Given

Android.xml:

<activity android:name='.IconListActivity'
  android:label='@string/icon_list_activity_name'
/>

Strings.xml:

<string name='icon_list_activity_name>Icon List</string>

How do I access to the string 'Icon List' given IconListActivity.class?

TrueWill
  • 25,132
  • 10
  • 101
  • 150
Scott
  • 7,034
  • 4
  • 24
  • 26
  • Can you please give a use-case where you wish to do so? Maybe we can find a workaround. Also, whether the IconListActivity.class is in same apk or not? – bhatt4982 Sep 22 '09 at 05:03
  • IconListActivity is an activity I'm writing while teaching myself Android programming. – Scott Sep 22 '09 at 15:46
  • why not just use `R.string.icon_list_activity_name` at the point where you need it? – gMale Feb 07 '15 at 19:35

5 Answers5

31

PackageManager#getActivityInfo() returns an ActivityInfo structure, which has a labelRes and a name field, one of which should have what you need.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
10

From any activity:

String label = null;
try {
    label = getResources().getString(
        getPackageManager().getActivityInfo(getComponentName(), 0).labelRes);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
Log.d(LOG_TAG, "Activity Label: " + label);
Jon
  • 9,156
  • 9
  • 56
  • 73
7

If you have the ComponentName, then you can do the following:

PackageManager pm = getPackageManager();
ActivityInfo activityInfo = pm.getActivityInfo (componentName, 0);
Log.d ("ActivityLabel", activityInfo.loadLabel (pm).toString ());
Shade
  • 9,936
  • 5
  • 60
  • 85
3

We have being trying to get the label but labelRes return 0 and name is the simple class name of the Activity.

The way we've managed to get the String from the label (we're targetting API 23, btw) was using the nonLocalizedLabel field:

ComponentName cn = new ComponentName(this, MainActivity.class);
ActivityInfo info = getPackageManager().getActivityInfo(cn, 0);
Log.d(LOG_TAG, "label == " + info.nonLocalizedLabel);
Henrique de Sousa
  • 5,727
  • 49
  • 55
0

According to the documentation for the activity element, the name xml attribute is for an Activity subclass, i.e. it is not anything to do with the name of the activity. labelRes is the field wanted here (corresponding to the label XML attribute).

darrenp
  • 4,265
  • 2
  • 26
  • 22