我正在尝试制作一个自定义ChedckBox,并且难以将按钮部分居中。这是代码:
<FrameLayout
android:layout_width="@dimen/checkbox_height"
android:layout_height="@dimen/checkbox_height"
android:background="@drawable/checkbox_background_info"
android:padding="5dp" >
<CheckBox
android:id="@+id/classification_uk_selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/checkbox_star_info">
</CheckBox>
</FrameLayout>
Drawbale只有一颗黄色的星星,没有启用背景,灰色禁用。它留在左侧,我不能让它居中
感谢您的帮助
答案 0 :(得分:1)
如果您将FrameLayout更改为RelativeLayout,您只需将android:center_in_parent设置为true;
答案 1 :(得分:0)
在您的框架布局中将重力设置为中心。 机器人:比重= “中心”
答案 2 :(得分:0)
我不相信这是可能的(至少不是API版本8)
这是来自CompoundButton.onDraw的代码,它似乎表明CompoundButton在一个边界矩形中绘制了buttonDrawable(它代表你的复选框图像),在父视图中偏移量为0。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final Drawable buttonDrawable = mButtonDrawable;
if (buttonDrawable != null) {
final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
final int height = buttonDrawable.getIntrinsicHeight();
int y = 0;
switch (verticalGravity) {
case Gravity.BOTTOM:
y = getHeight() - height;
break;
case Gravity.CENTER_VERTICAL:
y = (getHeight() - height) / 2;
break;
}
buttonDrawable.setBounds(0, y, buttonDrawable.getIntrinsicWidth(), y + height);
buttonDrawable.draw(canvas);
}
}
相反,尝试将CheckBox的宽度设置为略大于(dp),而不是您正在使用的图像的大小。这会挤压可绘制的按钮,并且不会使用右侧的所有空白区域进行渲染。