-1

我已经使用这个分段控制器库很长时间了,但是在 Android 7 下,图像不再绘制在单选按钮上......有没有人知道这个版本的 Android 发生了什么变化导致它停止工作?

segmentedcontrollerradiobutton 绘制,但应该在按钮上的图像不再绘制。

正在使用的图书馆:

https://github.com/vinc3m1/android-segmentedradiobutton

package com.makeramen.segmented;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioButton;

public class CenteredRadioImageButton extends RadioButton {

Drawable image;

public CenteredRadioImageButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, com.makeramen.segmented.R.styleable.CompoundButton, 0, 0);
    image = a.getDrawable(1);
    setButtonDrawable(android.R.color.transparent);
    a.recycle();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (image != null) {
        image.setState(getDrawableState());

        // scale image to fit inside button

        int imgHeight = image.getIntrinsicHeight();
        int imgWidth = image.getIntrinsicWidth();
        int btnWidth = getWidth();
        int btnHeight = getHeight();
        float scale;

        if (imgWidth <= btnWidth && imgHeight <= btnHeight) {
            scale = 1.0f;
        } else {
            scale = Math.min((float) btnWidth / (float) imgWidth,
                    (float) btnHeight / (float) imgHeight);
        }


        int dx = (int) ((btnWidth - imgWidth * scale) * 0.5f + 0.5f);
        int dy = (int) ((btnHeight - imgHeight * scale) * 0.5f + 0.5f);

        image.setBounds(dx, dy, (int)(dx + imgWidth * scale), (int)(dy + imgHeight * scale));

        image.draw(canvas);
    }
}
}

实际上,在 Android 7 中,IMAGE 值在运行时始终为 NULL。

 <com.makeramen.segmented.CenteredRadioImageButton
                    android:id="@+id/myButton"
                    android:layout_width="40dip"
                    android:layout_height="50dip"
                    android:button="@drawable/myImage"
                    android:clickable="true"
                    android:minWidth="40dip"
                    android:minHeight="33dip"
                    android:focusable="true">
                    </com.makeramen.segmented.CenteredRadioImageButton>
4

1 回答 1

0

想通了,在 7 中发生了一些变化...... TypedArray 中的索引从 1 变为 0...... 修改解决了这个问题。

于 2018-11-28T04:40:21.063 回答