Issue
I'm developing a basic paint application in android and I can't seem to programmatically set custom drawables for my radio buttons. These radio buttons consist of a LayerDrawable
with a white ColorDrawable
for the borders and an inset yellow (or whatever color it is) ColorDrawable
for the center. I put this LayerDrawable
along with another one (it has black borders to indicate selection) in a StateListDrawable
to preserve the RadioButton
functionality.
But when I try setButtonDrawable(myDrawable)
, the RadioButton
occupies a very small region even though I specify the width and height to be 30dp
.
And then when I try setButtonDrawable(null)
and setBackground(myDrawable)
, my RadioButton
no longer has its functionality.
Here is my code
private void setupColorButtons() {
int[] colors = {Color.RED, Color.GREEN, Color.BLUE,
Color.YELLOW, Color.CYAN, Color.MAGENTA};
int childCount = mColorGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
RadioButton colorButton = (RadioButton) mColorGroup.getChildAt(i);
colorButton.setButtonDrawable(createColorButtonDrawable(colors[i]));
}
}
private Drawable createColorButtonDrawable(int color) {
ColorDrawable center = new ColorDrawable(color);
ColorDrawable selBorder = new ColorDrawable(R.color.black);
ColorDrawable unselBorder = new ColorDrawable(R.color.white);
LayerDrawable sel = new LayerDrawable(new Drawable[] {selBorder, center});
sel.setLayerInset(1, 2, 2, 2, 2);
LayerDrawable unsel = new LayerDrawable(new Drawable[] {unselBorder, center});
unsel.setLayerInset(1, 2, 2, 2, 2);
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_checked}, sel);
states.addState(new int[] {-android.R.attr.state_checked}, unsel);
return states;
}
I've already looked at similar questions, but every solution requires me to create custom xml styles. I'm just wondering if anyone knows how to set a custom StateListDrawable
programmatically. Thanks in advance for any help!
Solution
Try this code:
StateListDrawable mState1 = new StateListDrawable();
mState1.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.button3_pressed));
mState1.addState(new int[] { android.R.attr.state_focused },
getResources().getDrawable(R.drawable.button3_focused));
mState1.addState(new int[] {},
getResources().getDrawable(R.drawable.button3_up));
myButton.setBackgroundDrawable(mState1);
Answered By - Leo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.