我有一个 ImageButton,它应该包含文本。为此,我使用 LayerDrawable(CustomViewFactory 类中的 createImage 方法)简而言之
public class CustomViewFactory extends ImageButton {
public CustomViewFactory createButton(String text) {
this.setBackgroundDrawable(createImage(R.drawable.back_configuration, text));
return this;
}
back_configuration.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/back_button_pressed" adroid:state_pressed="true"> </item>
<item android:drawable="@drawable/back_button_normal"></item>
<item android:drawable="@drawable/back_button_pressed" android:state_focused="true"/>
</selector>
back_button_normal 和 back_button_pressed - 9 个补丁 png 文件。
public LayerDrawable createImage(int resource, String text){
Drawable [] layers = new Drawable[2];
layers[0] = new TextDrawable(text);
layers[1] = r.getDrawable(R.drawable.back_configuration);
return new LayerDrawable(resource);
}
public class TextDrawable extends Drawable {
private final String text;
private final Paint paint;
public TextDrawable(String text) {
this.text = text;
this.paint = new Paint();
paint.setColor(Color.WHITE);
paint.setFilterBitmap(true);
paint.setTextSize(textSize);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
paint.setStyle(Paint.Style.FILL);
paint.setTextAlign(Paint.Align.LEFT);
}
@Override
public void draw(Canvas canvas) {
canvas.drawText(text, 0, 0, paint);
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
paint.setColorFilter(cf);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
问题。如果文本很大,则将其截断。如何根据里面的文字使 ImageButton 本身的大小增加。有哪些替代方法。
如果我使用按钮,图像会在按钮上拉伸
我为我的英语道歉。非常感谢你。