Hi,
I have a whole bunch of buttons that have different backgrounds.
I learnt about the Drawable Resources and the <selector> tag.
So I guess I need to make an XML file for every button?
I thought of making 1 image-file (per state) that has 32x32px reserved for every button's background. I would cut up the image and assign every piece to a button.
Of course I cannot do that in XML so I tried to use the StateListDrawable class.
But somehow it doesn't work.
Here's the code (createBitmap() returns the cutout piece as BitmapDrawable):
This is where I call the above method:
When I run the app it shows all buttons in the default state, and clicking it does not change a thing.
So the images are all cut up nicely, and assigned to buttons, but the states are not working.
Anybody know why?
I have a whole bunch of buttons that have different backgrounds.
I learnt about the Drawable Resources and the <selector> tag.
So I guess I need to make an XML file for every button?
I thought of making 1 image-file (per state) that has 32x32px reserved for every button's background. I would cut up the image and assign every piece to a button.
Of course I cannot do that in XML so I tried to use the StateListDrawable class.
But somehow it doesn't work.
Here's the code (createBitmap() returns the cutout piece as BitmapDrawable):
Code:
private Button createButton(int buttinIndex, int buttonWidth, int buttonHeight, int regular, int pressed, int focused)
{
StateListDrawable drawables = new StateListDrawable();
BitmapDrawable bitmapPressed = createBitmap(
pressed,
buttinIndex,
buttonWidth, buttonHeight);
BitmapDrawable bitmapFocused = createBitmap(
focused,
buttinIndex,
buttonWidth, buttonHeight);
BitmapDrawable bitmapRegular = createBitmap(
regular,
buttinIndex,
buttonWidth, buttonHeight);
drawables.addState(new int[]{android.R.attr.state_pressed}, bitmapPressed);
drawables.addState(new int[]{android.R.attr.state_focused}, bitmapFocused);
drawables.addState(new int[]{android.R.attr.state_enabled}, bitmapRegular);
drawables.addState(new int[]{-android.R.attr.state_enabled}, bitmapPressed);
Button result = new Button(this);
result.setBackgroundDrawable(drawables);
//result.setBackgroundResource(R.drawable.examplebutton);
return result;
}
This is where I call the above method:
Code:
i++;
Button imgButton = createButton(i-1, 32, 32, R.drawable.hangman_letters_regular, R.drawable.hangman_letters_pressed, R.drawable.hangman_letters_focused);
When I run the app it shows all buttons in the default state, and clicking it does not change a thing.
So the images are all cut up nicely, and assigned to buttons, but the states are not working.
Anybody know why?
