首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用LayerDrawable背景自动调整ImageButton大小

使用LayerDrawable背景自动调整ImageButton大小
EN

Stack Overflow用户
提问于 2012-08-15 17:34:22
回答 1查看 659关注 0票数 1

我有一个ImageButton,它应该包含文本。简而言之,我使用LayerDrawable ( CustomViewFactory类中的createImage方法)

代码语言:javascript
复制
 public class CustomViewFactory extends ImageButton {
    public CustomViewFactory createButton(String text) {
    this.setBackgroundDrawable(createImage(R.drawable.back_configuration, text));
    return this;
    }

back_configuration.xml

代码语言:javascript
复制
  <?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文件。

代码语言:javascript
复制
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本身的大小。有哪些替代方法。

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-08-15 17:45:56

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

编辑:检查如果对文本视图使用填充,则将其删除。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11967002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档