如何通过setButtonDrawable(以编程方式...)将togglebutton中的drawable居中

时间:2013-11-11 12:59:19

标签: android togglebutton

如何在没有指定文本内容的情况下将togglebutton的内容居中?

这是一个没有文字的togglebutton,但是对于每个州的图像。

编辑:好吧,我最终实现了自己的ToggleImageButton。

2 个答案:

答案 0 :(得分:0)

你不能。

我的解决方案是使用 CompoundButton

具有两种状态的按钮,已选中且未选中。按下或单击按钮时,状态会自动更改。

我将它作为我自己的类(扩展CompundButton),而不是在init函数中,

this.setBackground(ContextCompat.getDrawable(context, R.drawable.cell_toggle));

cell_toggle.xml(经典选择器)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@color/transparent"  />
<item android:state_checked="true">
    <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
        <solid
            android:color="@color/bright_sky_blue"/>
        <size
            android:width="20dp"
            android:height="20dp"/>
    </shape>
</item>

答案 1 :(得分:0)

togglebutton.buttonDrawable = ContextCompat.getDrawable(yourContext, R.drawable.your_drawable)

或在您的xml

<ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@drawable/your_drawable"/>
相关问题