2012-08-15 34 views
1

我有一個ImageButton,它應該包含文本。 爲此,我使用LayerDrawable(在CustomViewFactory類的createImage方法) 總之使用LayerDrawable背景Autoresize ImageButton

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本身的大小取決於文本內部。什麼是替代方法。

如果我使用該按鈕,圖像被拉伸按鈕

我爲我的英語道歉。非常感謝你。

回答

0

您可以嘗試使用TextView的,而不是ImageView的或ImageButton的,然後分配背景的文本視圖,你想要的形象,並設置你想要的TextView文本並使其WRAP_CONTENT爲layout_width

編輯:檢查如果你使用文本視圖的填充刪除它。

+0

謝謝!這真的很有用。有一個問題。文字不在中間。 http://imageshack.us/photo/my-images/855/26032627.png/ – 2012-08-15 10:13:07

+0

您可以將textView的重力屬性設置爲中心 – Amt87 2012-08-15 10:48:37

+0

android:gravity =「center」...如果答案適合您,您可以勾選它在左側 – Amt87 2012-08-15 10:49:31