您的位置:首页 > 移动开发 > Android开发

Android 从清单配置文件元数据中获取值

2015-08-11 15:21 423 查看
最近在上班工作当中,也尝到了一些新的知识,现总结如下
(1)从AndroidManifest.xml配置文件中获取meta数据

// 从Manifest.xml配置文件中获取数据
public static String getMetaValue(Context context, String metaKey) {
Bundle metaData = null;
String metaValue = null;
if (context == null || metaKey == null) {
return null;
}
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
if (null != ai) {
metaData = ai.metaData;
}
if (null != metaData) {
metaValue = metaData.getString(metaKey);
}
} catch (NameNotFoundException e) {
}
return metaValue;// xxx
}
<meta-data android:name="api_key" android:value="xxx" />


(2)获取layout文件中的一些控件,如下是一个Activity

public class CustomActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Resources resource = this.getResources();
String pkgName = this.getPackageName();

setContentView(resource.getIdentifier("custom_activity", "layout", pkgName));
    // 获取pkgName包下名为custom_activity的一个layout文件

TextView titleView = (TextView) this.findViewById(resource.getIdentifier("title", "id", pkgName));
    // 获取pkgName包下id为title的一个widget

}
}


之后在AndroidManifest.xml中,对该Activity进行配置,配置包名为完全路径名。
下面是查看resource.getIdentifier()方法分析

public int getIdentifier(String name, String defType, String defPackage) {
try {
return Integer.parseInt(name);
} catch (Exception e) {
// Ignore
}
return mAssets.getResourceIdentifier(name, defType, defPackage);
    // getResources().getIdentifier(name, defType, defPackage)
}


返回给定的resource_name所对应的标识符,类似于R文件中的id(个人理解)!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: