Issue
I have create a little custom view that extends ImageView.
My custom view provides a method showError(int)
, where I can pass a resource id, which should be displayed as the image views content. It would be great if I could pass a simple color resource id or a drawable resource id.
My problem is: how do I determine if the passed resource id is a Drawable or a Color?
My current approach is something like this:
class MyImageView extends ImageView{
public void showError(int resId){
try{
int color = getResources().getColor(resId);
setImageDrawable(new ColorDrawable(color));
}catch(NotFoundException e){
// it was not a Color resource so it must be a drawable
setImageDrawable(getResources().getDrawable(resId));
}
}
}
Is it safe to do that? My assumption is, that a resource id really unique. I mean not unique in R.drawable or R.color, but completely unique in R
So that there is no
R.drawable.foo_drawable = 1;
R.color.foo_color = 1;
Is it correct that the id 1
will be assigned only to one of this resources but not to both?
Solution
You probably want to look up a TypedValue
from the resources, to allow you to determine whether the value is a Color
or a Drawable
. Something like this should work without needing to throw and catch an exception:
TypedValue value = new TypedValue();
getResources().getValue(resId, value, true); // will throw if resId doesn't exist
// Check whether the returned value is a color or a reference
if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
// It's a color
setImageDrawable(new ColorDrawable(value.data));
} else if (value.type == TypedValue.TYPE_REFERENCE) {
// It's a reference, hopefully to a drawable
setImageDrawable(getResources().getDrawable(resId));
}
Answered By - Alex MDC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.