已經知道圖片資源的ID號是resid。如何獲取圖片資源的文件名?

呵呵,很簡單的一句代碼,可是我卻走了不少彎路
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.)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章