(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(个人理解)!