在我的清单中我有:
<application
android:name=".MyApp"
android:icon="@drawable/ic_launcher_icon"
android:label="@string/app_name"
android:debuggable="true">
Run Code Online (Sandbox Code Playgroud)
我如何获得标签元素?注意:我的代码在别人的内部运行,因此我无法访问@ string/app_name.
dar*_*enp 168
有一种比其他答案更简单的方法,它不需要您明确命名资源或担心包名称的异常.如果您直接使用字符串而不是资源,它也可以工作.
做就是了:
public static String getApplicationName(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
int stringId = applicationInfo.labelRes;
return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
编辑
根据Snicolas的评论,我修改了上面的内容,以便它不会尝试解析id,如果它是0.相反,它使用,nonLocalizedLabel
作为退避.不需要包装try/catch.
Vin*_*tti 51
如果在androidManifest.xml中的strings.xml/hardcoded中没有提到,无论是什么原因,比如android:label ="MyApp"
public String getAppLable(Context context) {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(context.getApplicationInfo().packageName, 0);
} catch (final NameNotFoundException e) {
}
return (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "Unknown");
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您知道String资源ID,那么您可以直接获取它
getString(R.string.appNameID);
Run Code Online (Sandbox Code Playgroud)
Hea*_*ers 35
public static String getApplicationName(Context context) {
return context.getApplicationInfo().loadLabel(context.getPackageManager());
}
Run Code Online (Sandbox Code Playgroud)
小智 22
从任何上下文使用:
getApplicationInfo().loadLabel(getPackageManager()).toString();
Run Code Online (Sandbox Code Playgroud)
Vip*_*hah 12
如果您知道包名称,请使用以下代码段
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(packageName, 0);
} catch (final NameNotFoundException e) {
ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
Run Code Online (Sandbox Code Playgroud)
在Kotlin 中,使用以下代码获取应用程序名称:
// Get App Name
var appName: String = ""
val applicationInfo = this.getApplicationInfo()
val stringId = applicationInfo.labelRes
if (stringId == 0) {
appName = applicationInfo.nonLocalizedLabel.toString()
}
else {
appName = this.getString(stringId)
}
Run Code Online (Sandbox Code Playgroud)
如果只需要应用程序名称而不是包名称,那么只需编写此代码即可.
String app_name = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
Run Code Online (Sandbox Code Playgroud)
在 Kotlin 中,它很简单:
val appLabel = context.applicationInfo.nonLocalizedLabel
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
99385 次 |
最近记录: |