Передайте рисованное изображение в TypedArray в Android - PullRequest
2 голосов
/ 12 декабря 2011

Я пытаюсь реализовать сегментированную радиокнопку отсюда: 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);
}

Пожалуйста, кто-нибудь, посоветуйте.Мне действительно нужна помощь.Спасибо.

1 Ответ

2 голосов
/ 13 декабря 2011

Вам необходимо добавить метод setImage к CenteredImageButton:

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

И просто позвоните позже в вашем основном коде:

button.setImage(drawable);

См. Этот Гист, чтобы увидеть метод inline: https://gist.github.com/1470789

Я также заметил, что вы изменили имя моего класса с CenteredRadioImageButton на CenteredImageButton. Если вы на самом деле не используете это для поведения, подобного RadioButton, я бы предложил использовать стандартный ImageButton

(я поддерживаю SegmentedRadioButton )

...