我正在尝试完成开发人员页面上给出的 android 示例。
它提供了两种在画布上绘图的方法。第一种方法是使用名为 CustomDrawableView 的类,如下所示:
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
public CustomDrawableView(Context context) {
super(context);
int x = 10;
int y = 10;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
然后由主类调用:
CustomDrawableView mCustomDrawableView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);
}
但随后教程说:
如果您想从 XML 布局而不是从 Activity 绘制此自定义可绘制对象,则 CustomDrawable 类必须重写 View(Context, AttributeSet) 构造函数,该构造函数在通过 XML 的膨胀实例化 View 时调用。然后将 CustomDrawable 元素添加到 XML,如下所示:
<com.example.shapedrawable.CustomDrawableView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
我已成功运行第一个示例,但我不知道如果我想采用第二个选项,我的代码应该是什么样子。
据推测,我从 @Override View 开始,但后来我陷入困境。
我想要这样做的原因是因为我想创建一个仅覆盖屏幕的一部分的画布,以便我可以在其他部分中容纳按钮和文本。