android drawable button,android RadioButton button drawable gravity

According to CompoundButton.onDraw() source code it's always left-aligned.

(Note the line buttonDrawable.setBounds(0, y, buttonDrawable.getIntrinsicWidth(), y + height);)

You will have to derive a new class from RadioButton and override onDraw().

EXAMPLE ADDED LATER:

Ok, so here's what you do. Firstly, here's a layout:

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:id="@+id/myview"

android:layout_width="fill_parent"

android:layout_height="100dp"

android:layout_centerInParent="true"

android:text="Button test"

/>

Secondly here's the custom-drawing RadioButtonCenter:

package org.test.TestProj;

import android.content.Context;

import android.content.res.TypedArray;

import android.util.AttributeSet;

import android.view.Gravity;

import android.widget.RadioButton;

import android.graphics.Canvas;

import android.graphics.drawable.Drawable;

public class RadioButtonCenter extends RadioButton {

public RadioButtonCenter(Context context, AttributeSet attrs) {

super(context, attrs);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CompoundButton, 0, 0);

buttonDrawable = a.getDrawable(1);

setButtonDrawable(android.R.color.transparent);

}

Drawable buttonDrawable;

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

if (buttonDrawable != null) {

buttonDrawable.setState(getDrawableState());

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;

}

int buttonWidth = buttonDrawable.getIntrinsicWidth();

int buttonLeft = (getWidth() - buttonWidth) / 2;

buttonDrawable.setBounds(buttonLeft, y, buttonLeft+buttonWidth, y + height);

buttonDrawable.draw(canvas);

}

}

}

Finally, here's an attrs.xml file you need to put in res/values so the code can get at platform-defined attributes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值