2012-08-15 50 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