Reputation: 2504
I'm working to create a health bar for a game and its failing: Thanks in advance!
//there a corresponding ImageView in the layout
healthLevel = (ImageView) findViewById(R.id.healthbar);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), "res/drawable/health.png");
//vertical bar cropped from top
clipDrawable = new ClipDrawable(bitmapDrawable, Gravity.BOTTOM, ClipDrawable.VERTICAL);
healthLevel.setImageDrawable(clipDrawable);
HelperClass.setHealth();
clipDrawable.setLevel(10000);
clipDrawable.invalidateSelf();
Log:
11-12 19:32:46.272: W/BitmapDrawable(10524): BitmapDrawable cannot decode res/drawable/health.png
Solution:
//there a corresponding ImageView in the layout
healthLevel = (ImageView) findViewById(R.id.healthbar);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.health);
//Convert Bitmap to Drawable
Drawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
//vertical bar cropped from top
clipDrawable = new ClipDrawable(bitmapDrawable, Gravity.BOTTOM, ClipDrawable.VERTICAL);
healthLevel.setImageDrawable(clipDrawable);
HelperClass.setHealth();
clipDrawable.setLevel(10000);
clipDrawable.invalidateSelf();
Upvotes: 0
Views: 1181
Reputation: 1512
As to your question, creating a BitmapDrawable
from a file path needs the file's absolute storage path rather than the relative path of your app package.
I've tried the following pieces of code and it works.
final ImageView iv = (ImageView) findViewById(R.id.image_view);
File file = new File("/storage/sdcard0/Download/ic_launcher.png");
BitmapDrawable bw = new BitmapDrawable(file.getAbsolutePath());
iv.setImageDrawable(bw);
However, i think that what you need is something like a Bitmap
which can be created with
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
You might find this toturial and this link helpful.
Upvotes: 2