使用LayerDrawable背景自动调整ImageButton

时间:2012-08-15 09:34:22

标签: android drawable imagebutton autoresize text-size

我有一个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本身的大小增加,具体取决于里面的文本。有哪些替代方法。

如果我使用按钮,图像会在按钮上拉伸

我为我的英语道歉。非常感谢你。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用textView而不是imageView或imageButton,然后为文本视图指定背景作为所需的图像,并为textView设置所需的文本,并使其成为layout_content for layout_width

修改:检查是否使用填充文本视图将其删除。

相关问题