Question

I have an ImageButton, which should contain the text. For this I use LayerDrawable (createImage method in CustomViewFactory class) In short

 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 and back_button_pressed - 9 patch png files.

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;
    }
}

Problem. If the text is large, then it is cut off. How to make ImageButton itself increased in size depending on the text inside. What are the alternative methods.

And if I use the Button, the image is stretched on the button

I apologize for my English. Thank you very much.

Was it helpful?

Solution

You can try using textView rather than imageView or imageButton and then assign background for the text view as the image you want and set the text you want for textView and make it wrap_content for layout_width

Edit: check if you use padding for the text view remove it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top