我使用以下 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
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...
}
}
在启动的 Activity 中,使用 setContentView(new DrawView(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 设置 Activity 的布局。将按钮和您的自定义 View 放在那里(如果您不希望它可见,可以将其设为“消失”)。
但在创建之前,您应该为您的 View 再添加一个构造函数
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
ball = new ColorBall(context,R.drawable.bol_groen, points);
}
关于Android:如何添加按钮和自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5509631/