我试图从此处实现分段单选按钮:https://github.com/makeramen/android-segmentedradiobutton,但是我需要以编程方式而不是XML设置图像。

这是自定义RadioButton的来源:

public class CenteredImageButton extends RadioButton {

    Drawable image;

    public CenteredImageButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.CompoundButton, 0, 0);
        image = a.getDrawable(1);
        setButtonDrawable(android.R.id.empty);

    }

    @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();
            Log.d("IMAGEHEIGHT", "imageWidth is " + imgHeight);

            int imgWidth = image.getIntrinsicWidth();
            Log.d("IMAGEWIDTH", "imageWidth is " + imgWidth);

            int btnWidth = getWidth();
            Log.d("BUTTONWIDTH", "buttonWidth is " + btnWidth);
            int btnHeight = getHeight();
            Log.d("BUTTONHEIGHT", "buttonHeight is " + btnHeight);

            float scale;

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

            Log.d("SCALE", "scale is " + scale);

            int dx = (int) ((btnWidth - imgWidth * scale) * 0.5f + 0.5f);
            Log.d("DX", "dx is " + dx);
            int dy = (int) ((btnHeight - imgHeight * scale) * 0.5f + 0.5f);
            Log.d("DY", "dy is " + dy);

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

            image.draw(canvas);
        }
    }


我在这样的另一个文件中设置可绘制对象:

private void setButtonImageProperties(RadioButton button,Drawable drawable){
    button.setGravity(Gravity.CENTER);
    Resources resources = this.context.getResources();
    float dipValue = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            60, resources.getDisplayMetrics());
    float dipValue1 = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 80, resources.getDisplayMetrics());

    button.setMinHeight((int) dipValue);
    button.setMinWidth((int) dipValue1);

    button.setButtonDrawable(drawable);
}


请任何人,指教。我真的需要伸出援手。谢谢。

最佳答案

您几乎需要向CenteredImageButton添加setImage方法:

public void setImage(Drawable newImage) {
    image = newImage;
}


然后稍后在您的主代码中调用它:

button.setImage(drawable);


请参见以下要点以查看内联方法:https://gist.github.com/1470789

我还注意到您将类的名称从CenteredRadioImageButton更改为CenteredImageButton。如果您实际上并未将其用于类似RadioButton的行为,我建议您使用标准的ImageButton

(我是SegmentedRadioButton的维护者)

07-27 21:44