Android:如何添加按钮和自定义视图
我使用以下视图来绘制位图并移动它。
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>
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...
}
}
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 xml 设置 Activity 的布局。将按钮和您的自定义视图放在那里(如果您不希望它可见,可以将其删除)。
但在制作之前,您应该为您的视图再添加一个构造函数
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