Android: How to add button and a custom view
I use the following View to draw a bitmap and move it around.
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.开发者_如何学Go..
}
}
In the starting Activity, the layout is set using setContentView(new DrawView(this));
I want add a button to the screen and when I click on the button, I want a new bitmap to be added. How do I add a button to this screen?
EDIT: This is my 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>
Set activity's layout from xml. Put there button and your custom view (you can make it GONE if you don't want it to be visible).
But before making it you should have one more constructor for your view
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
ball = new ColorBall(context,R.drawable.bol_groen, points);
}
精彩评论