Android:如何添加按钮和自定义视图
我使用下面的视图绘制位图并移动它Android:如何添加按钮和自定义视图,android,button,view,Android,Button,View,我使用下面的视图绘制位图并移动它 public class DrawView extends View { private ColorBall ball; public DrawView(Context context) { super(context); setFocusable(true); ball = new ColorBall(context,R.drawable.bol_groen, points); } @Override protec
public class DrawView extends View {
private ColorBall ball;
public DrawView(Context context) {
super(context);
setFocusable(true);
ball = new ColorBall(context,R.drawable.bol_groen, points);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null);
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// do stuff...
}
}
在开始活动中,使用setContentView(newdrawview(this))设置布局代码>
我想在屏幕上添加一个按钮,当我点击按钮时,我想添加一个新的位图。如何将按钮添加到此屏幕
编辑:这是我的main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button android:text="Button"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<com.example.DrawView
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
从xml设置活动的布局。将按钮和自定义视图放在那里(如果不想让它可见,可以将其删除)
但在创建它之前,您应该为视图再添加一个构造函数
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
ball = new ColorBall(context,R.drawable.bol_groen, points);
}
@罗希思:我觉得布局还可以。我从未在没有覆盖onMeasure方法的情况下创建自定义视图。尝试使用登录绘制方法来了解视图的实际大小和绘制位图的坐标。谢谢。让它工作起来。您还可以告诉我如何在单击按钮时添加位图。您应该为按钮设置ClickListener。在那里,可以将自定义视图的可见性设置为可见/消失。或者,您可以将要绘制的位图传递到视图并使其无效。