Я пытаюсь реализовать сегментированную радиокнопку отсюда: 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);
}
Пожалуйста, кто-нибудь, посоветуйте.Мне действительно нужна помощь.Спасибо.