Android 6上的ToggleButton:setCompoundDrawables不起作用

时间:2015-11-03 15:25:31

标签: android android-drawable android-6.0-marshmallow android-togglebutton

我已将此代码放在ToggleButton文本的右侧:

ToggleButton myToggle = (ToggleButton) v.findViewById(R.id.filtro_stat);
Drawable drawable = getResources().getDrawable(R.drawable.a010_ico);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.5),
            (int) (drawable.getIntrinsicHeight() * 0.5));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, Utils.dpToPixels(33,
            getActivity()), Utils.dpToPixels(26, getActivity()));

myToggle.setCompoundDrawables(null, null, sd.getDrawable(), null);
myToggle.setTextOn(getActivity().getString(R.string.string_on));
myToggle.setTextOff(getActivity().getString(R.string.string_off));

final int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    myToggle.setBackgroundDrawable(getResources().getDrawable(
            R.drawable.blue));
} else {
    myToggle.setBackground(getResources().getDrawable(
                R.drawable.blue));
}
myToggle.setChecked(false);

如果我在装有Android 6的设备上运行,则不会出现drawable,否则如果我在旧的Android版本上运行代码,一切正常。我该如何解决?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,这就是我修复它的方法:

创建de ScaleDrawable后:

drawable = sd.getDrawable();

drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.5),
            (int) (drawable.getIntrinsicHeight() * 0.5));

myToggle.setCompoundDrawables(null, null, drawable, null);