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


    最近在上班工作当中,也尝到了一些新的知识,现总结如下
    (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(个人理解)!

  • 相关阅读:
    Cypress安装使用(E2E测试框架)
    AirtestIDE详解(跨平台的UI自动化编辑器)
    Linux之自动化部署
    工作笔记 之 Python应用技术
    工作笔记 之 Linux服务搭建
    工作笔记 之 互联网实用技术
    Git全面应用
    Python-Thread(通俗易懂)
    php笔记(二)PHP类和对象之Static静态关键字
    php笔记(一)面向对象编程
  • 原文地址:https://www.cnblogs.com/a284628487/p/3111814.html
Copyright © 2020-2023  润新知