自定义视图按钮onDraw()方法不绘制

时间:2014-07-04 15:25:47

标签: android android-layout android-custom-view android-button

如果我扩展按钮并覆盖onDraw方法以绘制某些内容(例如圆圈)并使用XML布局文件:

<view class = "com.example.button.MainActivity$MyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

出现圆圈,但如果我使用此

<Button class = "com.example.button.MainActivity$MyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

相反,除按钮的默认矩形视图外,不显示任何内容。 为什么? 自定义按钮类实现在 extending android button by using onDrawonDraw()方法是:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setStrokeWidth(10);
    paint.setStyle(Style.FILL);
    int width = canvas.getWidth();
    int height = canvas.getHeight();
    canvas.drawCircle(width/2, height/2, height/3, paint);
} 

1 个答案:

答案 0 :(得分:1)

如果要在xml布局中使用内部类,则语法始终为:

<view class = "com.example.button.MainActivity$MyButton"
    ...
/>

如果使用<Button ...,则会忽略class属性,这就是为什么它会膨胀并绘制标准Button小部件。

如果您希望MyButton成为Button,请让其类扩展它。您根本不需要更改xml。

相关问题