我有一个几乎完成的应用程序,它使用 ExpandableListView,每个子行都有一个切换按钮。我可以很好地使用 CheckBox 或 ToggleButton,但底层的 CompoundButton 不支持按钮图形的水平居中(wtf?)。所以我建立了自己的,但以某种方式使用它而不是使它在列表视图中不可点击。
在常规布局中,自定义复合按钮可以完美运行。
一些魔法咒语似乎不见了,我不太确定那会是什么。我会感谢你的任何见解。
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);
}
}
}