码迷,mamicode.com
首页 > 移动开发 > 详细

Android使用getIdentifier()方法根据资源名来获取资源id

时间:2016-11-25 12:38:07      阅读:508      评论:0      收藏:0      [点我收藏+]

标签:demo示例   class   roc   enter   com   returns   style   工具栏   poi   

有时候我们想动态的根据一个资源名获得到对应的资源id,就可以使用getResources().getIdentifier()方法来获取该id。然后再使用该id进行相关的操作。

1、Demo示例

下面用一个小Demo来讲解如何使用getResources().getIdentifier()方法来获取该id。

例如,新建一个Android项目,项目结构部分截图如下所示:
技术分享

MainActivity代码如下:

package com.oyp.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private ImageView mImageView;

    private ImageView mipmapImageView;

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取布局文件资源的ID
        int layoutId = getResources().getIdentifier("activity_main", "layout", getPackageName());
        Log.d(TAG, "----> 获取到的图片资源 drawableId= " + layoutId);

        //获取图片资源的ID
        mImageView = (ImageView) findViewById(R.id.imageView);
        int drawableId = getResources().getIdentifier("oyp", "drawable", getPackageName());
        mImageView.setImageResource(drawableId);
        Log.d(TAG, "----> 获取到的图片资源 drawableId=" + drawableId);


        mipmapImageView = (ImageView) findViewById(R.id.mipmapImageView);
        int mipmapId = getResources().getIdentifier("ic_launcher", "mipmap", getPackageName());
        mipmapImageView.setImageResource(mipmapId);
        Log.d(TAG, "----> 获取到的图片资源 mipmapId=" + mipmapId);

        //获取字符串资源
        mTextView = (TextView) findViewById(R.id.textView);
        int stringId = getResources().getIdentifier("author", "string", getPackageName());
        mTextView.setText(stringId);
        Log.d(TAG, "----> 获取到的字符串资源 stringId=" + stringId);
    }
}

布局文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.oyp.demo.MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/title" />
    <ImageView
        android:id="@+id/mipmapImageView"
        android:layout_below="@id/title"
        android:layout_marginTop="40dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dip" />

</RelativeLayout>

用到的strings.xml字符串资源代码如下:

<resources>

    <string name="app_name">Demo</string>
    <string name="title">利用getIdentifier()方法获取资源ID</string>
    <string name="author">欧阳鹏 http://blog.csdn.net/ouyang_peng</string>

</resources>

运行该程序,运行效果如下所示:
技术分享

打印出来的log为:

11-24 22:15:02.471 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId= 2130968601
11-24 22:15:02.476 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId=2130837579
11-24 22:15:02.477 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 mipmapId=2130903040
11-24 22:15:02.477 12023-12023/com.oyp.demo D/MainActivity: ----> 获取到的字符串资源 stringId=2131099669

我们打开编译好后的 com.oyp.demo.R文件
技术分享

技术分享

首先来看看activity_main这个layout的id是不是和我们打印出来的一样是2130968601,如下图所示,在 com.oyp.demo.R文件中,activity_main的值确实是2130968601
技术分享

部分代码如下所示:

public static final class layout {
        ......

        public static final int abc_screen_simple = 2130968595;
        public static final int abc_screen_simple_overlay_action_mode = 2130968596;
        public static final int abc_screen_toolbar = 2130968597;
        public static final int abc_search_dropdown_item_icons_2line = 2130968598;
        public static final int abc_search_view = 2130968599;
        public static final int abc_select_dialog_material = 2130968600;
        public static final int activity_main = 2130968601;
        public static final int notification_media_action = 2130968602;
        public static final int notification_media_cancel_action = 2130968603;
        public static final int notification_template_big_media = 2130968604;
        public static final int notification_template_big_media_narrow = 2130968605;

        ......

        public layout() {
        }
    }

drawable类型的图片 ic_launcher 的资源id 为 2130903040

 public static final class mipmap {
        public static final int ic_launcher = 2130903040;

        public mipmap() {
        }
    }

drawable类型的图片 oyp 资源id为 2130837579

public static final class drawable {
        ......

        public static final int abc_textfield_search_material = 2130837578;
        public static final int notification_template_icon_bg = 2130837580;
        public static final int oyp = 2130837579;

        public drawable() {
        }
    }

String类型的资源author id为 2131099669

public static final class string {

        ......

        public static final int app_name = 2131099668;
        public static final int author = 2131099669;
        public static final int status_bar_notification_info_overflow = 2131099667;
        public static final int title = 2131099670;

        public string() {
        }
    }

可以发现打印出来的资源id和com.oyp.demo.R文件生成的资源id是一致的,因此使用getResources().getIdentifier()方法完全可以正确地获取资源的id。

2、getIdentifier()方法封装

点击查看getIdentifier()方法源代码如下所示:

/**
     * Return a resource identifier for the given resource name.  A fully
     * qualified resource name is of the form "package:type/entry".  The first
     * two components (package and type) are optional if defType and
     * defPackage, respectively, are specified here.
     * 
     * <p>Note: use of this function is discouraged.  It is much more
     * efficient to retrieve resources by identifier than by name.
     * 
     * @param name The name of the desired resource.
     * @param defType Optional default resource type to find, if "type/" is
     *                not included in the name.  Can be null to require an
     *                explicit type.
     * @param defPackage Optional default package to find, if "package:" is
     *                   not included in the name.  Can be null to require an
     *                   explicit package.
     * 
     * @return int The associated resource identifier.  Returns 0 if no such
     *         resource was found.  (0 is not a valid resource ID.)
     */
    public int getIdentifier(String name, String defType, String defPackage) {
        if (name == null) {
            throw new NullPointerException("name is null");
        }
        try {
            return Integer.parseInt(name);
        } catch (Exception e) {
            // Ignore
        }
        return mAssets.getResourceIdentifier(name, defType, defPackage);
    }

技术分享

第一个参数为资源ID名,第二个为资源属性的类型,第三个为包名。

下面是一个封装好的工具栏,可以直接用来获取资源id。

package com.oyp.demo;

import android.content.Context;

/**
 * 工具类,可以通过资源名来获取资源id
 * </p><br/><br/><br/>
 * <a href = " http://blog.csdn.net/ouyang_peng "> 欧阳鹏博客</a>
 */
public class ResourceUtil {

    public static int getId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "id");
    }

    public static int getLayoutId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "layout");
    }

    public static int getStringId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "string");
    }

    public static int getDrawableId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "drawable");
    }

    public static int getMipmapId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "mipmap");
    }

    public static int getColorId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "color");
    }

    public static int getDimenId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "dimen");
    }

    public static int getAttrId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "attr");
    }

    public static int getStyleId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "style");
    }

    public static int getAnimId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "anim");
    }

    public static int getArrayId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "array");
    }

    public static int getIntegerId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "integer");
    }

    public static int getBoolId(Context context, String resourceName) {
        return getIdentifierByType(context, resourceName, "bool");
    }

    private static int getIdentifierByType(Context context, String resourceName, String defType) {
        return context.getResources().getIdentifier(resourceName,
                defType,
                context.getPackageName());
    }
}



将封装好的com.oyp.demo.ResourceUtil类应用到刚才的MainActivity中,代码如下:

package com.oyp.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private ImageView mImageView;

    private ImageView mipmapImageView;

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取布局文件资源的ID
//        int layoutId = getResources().getIdentifier("activity_main", "layout", getPackageName());
        int layoutId = ResourceUtil.getLayoutId(this, "activity_main");
        Log.d(TAG, "----> 获取到的布局文件资源 drawableId= " + layoutId);

        //获取图片资源的ID
        mImageView = (ImageView) findViewById(R.id.imageView);
//        int drawableId = getResources().getIdentifier("oyp", "drawable", getPackageName());
        int drawableId = ResourceUtil.getDrawableId(this, "oyp");
        mImageView.setImageResource(drawableId);
        Log.d(TAG, "----> 获取到的图片资源 drawableId=" + drawableId);


        mipmapImageView = (ImageView) findViewById(R.id.mipmapImageView);
//        int mipmapId = getResources().getIdentifier("ic_launcher", "mipmap", getPackageName());
        int mipmapId = ResourceUtil.getMipmapId(this, "ic_launcher");
        mipmapImageView.setImageResource(mipmapId);
        Log.d(TAG, "----> 获取到的图片资源 mipmapId=" + mipmapId);

        //获取字符串资源
        mTextView = (TextView) findViewById(R.id.textView);
//        int stringId = getResources().getIdentifier("author", "string", getPackageName());
        int stringId = ResourceUtil.getStringId(this, "author");
        mTextView.setText(stringId);
        Log.d(TAG, "----> 获取到的字符串资源 stringId=" + stringId);

        int colorId = ResourceUtil.getColorId(this , "colorPrimary");
        Log.d(TAG, "----> 获取到的颜色资源 colorId=" + colorId);

        int dimenId = ResourceUtil.getDimenId(this , "abc_dialog_min_width_major");
        Log.d(TAG, "----> 获取到的颜色资源 dimenId=" + dimenId);

        int integerId = ResourceUtil.getIntegerId(this , "abc_config_activityDefaultDur");
        Log.d(TAG, "----> 获取到的integer资源 integerId=" + integerId);

        int boolId = ResourceUtil.getBoolId(this , "abc_allow_stacked_button_bar");
        Log.d(TAG, "----> 获取到的bool资源 boolId=" + boolId);


        int attrId = ResourceUtil.getAttrId(this , "actionBarDivider");
        Log.d(TAG, "----> 获取到的attr资源 attrId=" + attrId);

    }
}

打印出来的Log日志为:

11-24 23:44:16.911 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的布局文件资源 drawableId= 2130968601
11-24 23:44:16.916 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 drawableId=2130837579
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的图片资源 mipmapId=2130903040
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的字符串资源 stringId=2131099669
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的颜色资源 colorId=2131427347
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的颜色资源 dimenId=2131230730
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的integer资源 integerId=2131361793
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的bool资源 boolId=2131165184
11-24 23:44:16.918 8543-8543/com.oyp.demo D/MainActivity: ----> 获取到的attr资源 attrId=2130772027

作者:欧阳鹏 欢迎转载,与人分享是进步的源泉!
转载请保留原文地址:
http://blog.csdn.net/ouyang_peng/article/details/53261599

技术分享

Android使用getIdentifier()方法根据资源名来获取资源id

标签:demo示例   class   roc   enter   com   returns   style   工具栏   poi   

原文地址:http://blog.csdn.net/ouyang_peng/article/details/53328000

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!