I have a nearly finished app that uses an ExpandableListView, and a single toggle button per each child row. I can use a CheckBox or a ToggleButton fine, but the underlying CompoundButton does not support horizontal centering of the button graphic (wtf?). So I built my own, but somehow using it instead renders it unclickable in the listview.
In a regular layout, the custom compoundbutton works perfectly.
Some magic incantation appears missing and I'm not quite sure what that would be. I'll thank you for any insights.
package net.shangtai.listener;
import android.widget.CompoundButton;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
class ImageToggle extends CompoundButton {
private Drawable buttonDrawable;
public ImageToggle(Context context) {
super(context, null);
}
public ImageToggle(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public ImageToggle(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setButtonDrawable(Drawable d) {
super.setButtonDrawable(d);
buttonDrawable=d;
}
@Override
protected void onDraw(Canvas canvas) {
if (buttonDrawable != null) {
final int gravity = getGravity();
final int height = buttonDrawable.getIntrinsicHeight();
final int width = buttonDrawable.getIntrinsicWidth();
int top=0;
int bottom=0;
int left=getWidth();
int right=getHeight();
switch (gravity) {
case Gravity.TOP:
top=0;
bottom=height;
break;
case Gravity.BOTTOM:
top=getHeight() - height;
bottom=0;
break;
case Gravity.CENTER_VERTICAL:
top=(getHeight() - height)/2;
bottom=top+height;
break;
case Gravity.LEFT:
left=0;
right=width;
break;
case Gravity.RIGHT:
left=getWidth() - width;
right=0;
break;
case Gravity.CENTER_HORIZONTAL:
left=(getWidth() - width)/2;
right=left+width;
break;
case Gravity.CENTER:
left=(getWidth() - width)/2;
right=left+width;
top=(getHeight() - height)/2;
bottom=top+height;
break;
}
buttonDrawable.setBounds(left, top, right, bottom);
buttonDrawable.draw(canvas);
}
}
}