已经知道图片资源的ID号是resid。如何获取图片资源的文件名?

在Android开发中,如果已知图片资源的ID(resid),可以通过Resources的getIdentifier方法结合上下文获取图片资源的文件名。首先获取Resources对象,然后调用getIdentifier方法,传入资源ID对应的包名、类型和名称。如果找到资源,返回的ID大于0,否则为0。注意,使用资源ID直接获取资源比通过名称更高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

呵呵,很简单的一句代码,可是我却走了不少弯路
view.getResources().getResourceName(resid)


单击相册中的图片,显示该图片的名字,源码如下。
@Override
public View getView( int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85,85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8, 8, 8);
}else{
imageView = (ImageView)convertView;
}
final Integer resid = mThumbIds[position];
imageView.setImageResource(mThumbIds[position]);
imageView.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Toast.makeText(mContext, v.getResources().getResourceName(resid).split("/")[1], 5).show();
}
});
return imageView;
}

这个方法所在的类继承BaseAdapter,而该方法是重写getView方法。



android 通过资源名称去获得资源R id

Resources resources = context.getResources();
int indentify = resources.getIdentifier(context.getPackageName()+":drawable/"+iconName, null, null);
if(indentify>0){
icon = resources.getDrawable(indentify);
}

以下是getIdentifier的API文档,可见最重要的是第一个参数,格式是:包名 + : + 资源文件夹名 + / +资源名
如果找到了,返回资源Id,如果找不到,返回0
public int getIdentifier (String name, String defType, String defPackage)
Since: API Level 1
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.
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Parameters
name The name of the desired resource.
defType Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
defPackage Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.
Returns
int The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值