kakka47
kakka47

Reputation: 3509

How can I use images as numbers/letters in Android?

I am developing an app where I need to show a count. This count is going to show for example a "4", then a "4 + 1", then finally a "5". I have .png images that I want to use as background to the numbers, so that I can easily show anything up to "99" if I need to.

So basically, I would like to assign a drawable background to a number. Is a custom font the way to go? Here typeface and view group with assigned strings is mentioned. Anyone tried this?

Upvotes: 2

Views: 1402

Answers (2)

Gabriel Negut
Gabriel Negut

Reputation: 13960

HashMap<char, Drawable> charMap = new HashMap(Character, Drawable>();
Resources res = getResources();
charMap.put('0', new Drawable(res, R.drawable.img_0));
charMap.put('1', new Drawable(res, R.drawable.img_1));
// the rest of the characters you want to use

When you want to retrieve the correct image for a character:

char c = '0';
Drawable charImage = charMap.get(c);

Upvotes: 2

Esben Andersen
Esben Andersen

Reputation: 823

Actually you just need an array of size 10:

Resources res = getResources();
Drawable numbers = new Drawable[10]{
   new Drawable(res, R.drawable.zero),
   new Drawable(res, R.drawable.one),
   new Drawable(res, R.drawable.two),
   ...
   new Drawable(res, R.drawable.nine)
};

and to get them just use:

int i = 5;
Drawable image = numbers[i];

If the number has 2 digits then you can put in 2 pictures etc.

You can also make a very big array, but that would honestly be a waste of lines. Also the space required when you only use 10 pictures is significantly smaller

Upvotes: 2

Related Questions