将可绘制图像传递给Android中的TypedArray
问题描述:
我想实现这里的分段单选按钮:https://github.com/makeramen/android-segmentedradiobutton但我需要以编程方式设置图像,而不是使用XML。将可绘制图像传递给Android中的TypedArray
这是自定义单选来源:
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);
}
请任何人,劝。我真的需要帮助。谢谢。
答
你几乎需要一个setImage方法添加到CenteredImageButton:
public void setImage(Drawable newImage) {
image = newImage;
}
后来只是把它在你的主代码:
button.setImage(drawable);
看到这个要点,看看该方法内联:https://gist.github.com/1470789
我也注意到你把我的类的名字从CenteredRadioImageButton改成了CenteredImageButton。如果你不实际使用此为单选按钮类似的行为,我会建议使用标准ImageButton
(我的SegmentedRadioButton维护者)
+1
你先生是上帝!非常感谢! – user788511
究竟不起作用? – 2011-12-12 11:32:50
我只需要一种方式来调用或引用CenteredImageButton类的图像..任何想法? – user788511
请任何人帮忙? – user788511