Android 具有分层可绘制背景的自动调整图像按钮大小
我有一个ImageButton,它应该包含文本。 为此,我使用LayerDrawable(CustomViewFactory类中的createImage方法) 总之 back_configuration.xmlAndroid 具有分层可绘制背景的自动调整图像按钮大小,android,drawable,imagebutton,autoresize,text-size,Android,Drawable,Imagebutton,Autoresize,Text Size,我有一个ImageButton,它应该包含文本。 为此,我使用LayerDrawable(CustomViewFactory类中的createImage方法) 总之 back_configuration.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item an
<?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>
问题。如果文本较大,则会将其截断。如何使ImageButton本身根据内部文本的大小而增大。有哪些替代方法
如果我使用这个按钮,图像会在按钮上拉伸
我为我的英语道歉。多谢各位 您可以尝试使用textView而不是imageView或imageButton,然后将文本视图的背景指定为所需的图像,并为textView设置所需的文本,并将其包装为布局宽度的内容
编辑:检查是否对文本视图使用了填充,然后将其删除。谢谢!这真的很有效。有一个问题。正文不在中间。您可以将textView的重力属性设置为centerandroid:gravity=“center”。。。如果答案对您有效,您可以在左侧勾选“设置重力(中心)”,表示文本视图不起作用。这是第一次,我担心的是,重力作用,但图像和文本不匹配。我设置了10行。看见
<?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>
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;
}
}