我必须创建一个按钮,如下图所示:
几乎可以,就像这样:
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/main_shape_button"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/colorSecundary"
android:textAlignment="viewStart"
android:drawableLeft="@drawable/ico_alerta"
android:drawableRight="@drawable/ico_seta_r"
android:text="@string/main_botao_painel_alertas" />
“@ drawable / main_shape_button”如下:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="-1dp" android:right="-1dp" android:bottom="-1dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke android:width="1dp" android:color="#ffffff" />
</shape>
</item>
</layer-list>
但是,我仍然需要添加黄色指示器以及用户的未查看警报数。
我怎样才能实现它?
我实现了扩展按钮类:
public class AlertButton extends Button {
public AlertButton(Context context) {
super(context);
}
public AlertButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AlertButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int h = canvas.getHeight();
int w = canvas.getWidth();
//Calculate the x coordinate
float xCoodinate = (3*w)/4;
//Calculate 80% of the button height to the ratio.
float ratio = (h/2) * 0.8f;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(getResources().getColor(R.color.colorTertiary));
canvas.drawCircle(x, h/2 , ratio, paint);
Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(50f);
textPaint.setAntiAlias(true);
textPaint.setTextAlign(Paint.Align.CENTER);
String text = "10";
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
float yCoordinate = 71f; //hard coded
canvas.drawText(text, x, yCoordinate, textPaint);
}
}
但是我没有发现如何计算正在绘制的文本的y坐标。
我怎么做?
答案 0 :(得分:2)
而不是Button
我会创建一个具有所需外观的布局,并使其android:clickable="true"
属性可以点击。
另一个选择是通过扩展Component
并覆盖其适当的方法来创建自己的自定义Button
。
检查this link以获取有关自定义组件的更多信息。
答案 1 :(得分:0)
将属性添加到android:clickable =“true”
<Button
android:id="@+id/your_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/main_shape_button"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/colorSecundary"
android:textAlignment="viewStart"
android:drawableLeft="@drawable/ico_alerta"
android:drawableRight="@drawable/ico_seta_r"
android:clickable="true"
android:text="@string/main_botao_painel_alertas" />