首先我是android的新手。
好的,这就是。
我试图覆盖按钮的onDraw,因为我想创建一个不同的样式按钮..有些东西有点不同。
现在我可以很容易地绘制背景,但我不能为我的生活弄清楚为什么我的按钮上没有文字。
public class TriButton extends Button {
private Paint m_paint = new Paint();
private int m_color = 0XFF92C84D; //LIKE AN OLIVE GREEN..
public TriButton(Context context) {
super(context);
setBackgroundColor(Color.BLACK);
}
public void onDraw(Canvas iCanvas) {
//draw the button background
m_paint.setColor(m_color);
iCanvas.drawRoundRect(new RectF(0, 0,getWidth(),getHeight()), 30, 30, m_paint);
//draw the text
m_paint.setColor(Color.WHITE);
iCanvas.drawText( "bash is king", 0, 0, m_paint);
}
public static RelativeLayout.LayoutParams GetRelativeParam(int iLeft, int iTop, int iWidth, int iHeight){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(iHeight, iWidth);
params.leftMargin = iLeft;
params.topMargin = iTop;
return params;
}
}
这是创建按钮的代码。
RelativeLayout relLay = new RelativeLayout(this);
m_button = new TriButton(this);
setContentView(relLay);
relLay.addView(m_button, m_button.GetRelativeParam(0,0,100,500) );
现在我读过的所有内容都让我期待在我的橄榄绿按钮椭圆形按钮中看到文字。 橄榄绿色的椭圆形出现了,但它没有文字。它是一个空洞。一种绿色的污迹,嘲笑我,让我想起它的沉默,我完全孤独:(。
答案 0 :(得分:3)
通常你会通过xml。
for examle将以下内容放在自定义类的布局中:
android:background="@drawable/shape"
然后将shape.xml放在/ drawable中。
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2px"
android:color="#555555"/>
<corners
android:radius="10px"/>
<gradient
android:startColor="#000000"
android:endColor="#ffffff"
android:angle="90"/>
</shape>
此示例创建一个带边框和渐变的圆角矩形。如果您需要进一步解释,请告诉我。
答案 1 :(得分:1)
好吧,我想,它不可见,因为坐标是按钮左下角的(0,0),所以文字不可见。试试这个并且它有效:
iCanvas.drawText( "bash is king", 0, 15, m_paint);
橄榄绿是一个不错的选择顺便说一句:)
答案 2 :(得分:0)
要在按钮中绘制文本,请在按钮类的onDraw中删除对drawText()的调用。您需要做的就是在按钮实例上调用setText,因为Button扩展了视图:
m_button.setText("bash is king");
此外,要制作自定义按钮,您可能需要考虑仅使用图像并为其分配OnClickListener。