Android利用资源名称获取其ID(一)--->getIdentifier()
发布日期:2021-06-30 11:14:45 浏览次数:2 分类:技术文章

本文共 1409 字,大约阅读时间需要 4 分钟。

MainActivity如下:
package cc.wy;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.widget.ImageView;import android.widget.TextView;/** * Demo描述: * 利用getIdentifier()方法获取资源ID *  * 方法描述: * getIdentifier(String name, String defType, String defPackage) * 第一个参数:资源的名称 * 第二个参数:资源的类型(drawable,string等) * 第三个参数:包名 */public class MainActivity extends Activity {	private Context mContext;	private ImageView mImageView;	private TextView mTextView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        init();    }        private void init(){    	mContext=this;    	//获取图片资源的ID    	mImageView=(ImageView) findViewById(R.id.imageView);    	int drawableId = mContext.getResources().getIdentifier("ic_launcher","drawable", mContext.getPackageName());    	mImageView.setImageResource(drawableId);    	System.out.println("----> 获取到的图片资源 drawableId="+drawableId);    	    	//获取字符串资源    	mTextView=(TextView) findViewById(R.id.textView);    	int stringId = mContext.getResources().getIdentifier("hello","string", mContext.getPackageName());    	mTextView.setText(stringId);    	System.out.println("----> 获取到的字符串资源 stringId="+stringId);    }}
main.xml如下:
strings.xml如下:
Hello World, MainActivity!
TestGetIdentifier

转载地址:https://it9527.blog.csdn.net/article/details/21017889 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android获取asset下的资源图片
下一篇:Android利用资源名称获取其ID(二)--->反射

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月21日 11时10分26秒