Android:如何添加按钮和自定义 View

标签 android button view

我使用以下 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/

相关文章:

android - 阵列适配器不更新

java - 如果网络可用,则从服务器获取 JSON

android - Phonegap 中的快速点击按钮

drupal - drupal 的喜欢和收藏按钮

android - 如何通过任何文件资源管理器更改图像背景

ruby-on-rails - 用纯 Ruby 编写 Rails 模板

android - 保存 Activity 中的数字以便稍后再次使用

android - 如何从 Linux 家庭服务器上传 Android 应用程序中的 sqlite 文件

button - javafx 多个按钮到同一个处理程序

asp.net-mvc - ASP.NET Mvc 站点中登录用户的自定义目录