我的应用程序中有一个按钮,我在其中设置它的背景: setBackground(可绘制背景)
然后我使用setText(CharSequence,TextView.BufferType)在底部显示文本。
现在问题是我试图在文本上添加圆形背景。我正在查看android文档的按钮,但我找不到任何有用的功能来为一个按钮的文本添加背景。
更清楚: Image http://i41.tinypic.com/1hc9og.png
我想要获得黄色部分。任何帮助/建议将不胜感激。谢谢!
编辑:要清楚红色形状是按钮本身。黄色的形状是我想要的按钮文本背景。
答案 0 :(得分:0)
您可以使用XML
作为按钮的自定义背景,根据需要为其提供样式,例如
round_button_file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#6F2500"/>
<stroke android:width="2sp" android:color="#fff" />
然后将按钮的背景设置为该XML文件
code for button
<Button
android:layout_width="30sp"
android:layout_height="30sp"
android:background="@drawable/round_button_file"
android:gravity="center_vertical|center_horizontal"
android:text="Text"
android:textColor="#fff" />
希望我帮助过。
答案 1 :(得分:0)
试试这个:
oval_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#FFFF00"/>
</shape>
oval_text.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_margin="10dp"
android:gravity="center_vertical|center_horizontal"
android:background="@drawable/oval_background"
android:text="TEXT"/>
</LinearLayout>
答案 2 :(得分:0)
我知道这是一个很老的帖子,但我认为这可以帮助很多。而不是使用drawable,而是尝试扩展按钮并在画布上绘制椭圆。
这里是:
public class YourButton extends Button {
//declare needed variables
private Context context;
private Paint ovalPaint;
public YourButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
this.context = context;
ovalPaint = new Paint();
ovalPaint.setAntiAlias(true);
ovalPaint.setStyle(Paint.Style.FILL);
ovalPaint.setColor(context.getResources().getColor(R.color.YOUR_RED_COLOR);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawOval(getOval(canvas), ovalPaint);
super.onDraw(canvas); //important
}
private RectF getOval(Canvas canvas) {
int offset = (int)(canvas.getWidth() * .05);
return new RectF(0 + offset, 0 + offset, canvas.getWidth() - offset, canvas.getHeight() - offset);
}
}
并按如下方式设置xml文件:
<YourButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Text"
android:textSize="30sp"
android:textColor="#fff" />