草庐IT

java - 如何为 Android 自定义 View 添加 OnClick 事件

coder 2023-11-30 原文

我有两个图像在屏幕上移动,一个是球,一个是人。 我想要发生的是当用户触摸男人的形象时,球会掉落。

我的问题是我似乎无法添加 onclick/ontouch 事件并使其正常工作。

我没有正确实现它,有人可以帮忙吗?

我已经包含了下面的 3 个类。格雷格是那个人,球被命名为球:)

TestAnimationActivity.java

 package com.test.firstAnimation;

    import android.app.Activity;
    import android.os.Bundle;

    public class TestAnimationActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new MyAnimationView(this));
       }
    }

Sprite .java

package com.test.firstAnimation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class Sprite extends View implements OnClickListener{

     private static int gregCoordX = 410; // the x coordinate at the canvas for greg
     private Bitmap img; // the image of Greg
     private Bitmap img2; // the image of pointer 
     private static int gregCoordY = 125; // the y coordinate at the canvas for greg
     private static int pointCoordX = 10;
     private static int pointCoordY = 10;
     private static int count = 1;
     private static int ballSpeed = 25;
     private static boolean goingRight = false;
     private static boolean goingLeft = true;
     private static boolean pointerGoingRight = false;
     private static boolean pointerGoingLeft = true;


    public Sprite(Context context, int drawable) {

        super(context);

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        img = BitmapFactory.decodeResource(context.getResources(), drawable);
        img2 = (BitmapFactory.decodeResource(context.getResources(), drawable));
        count++;
    }

    public static int getCount() {
        return count;
    }

    void setX(int newValue) {
        gregCoordX = newValue;
    }

    public static int getX() {
        return gregCoordX;
    }

    public static int getY() {
        return gregCoordY;
    }

    public static int getBX() {
        return pointCoordX;
    }

    public static int getBY() {
        return pointCoordY;
    }

    public Bitmap getBitmap() {
        return img;
    }

    public Bitmap getImg2() {
        return img2;
    }

    public static void dropBall()
    {
        pointCoordY++;
    }

    public static void moveBall(int x) {

           // check the borders
            //if more than ten go right
            //if ten go left
            //if more than 250 go left
            if (x <= 10 && pointerGoingLeft)
            {
            pointCoordX = pointCoordX + ballSpeed;
            pointerGoingRight = true;
            pointerGoingLeft = false;
            }
            else if (x >= 410 && pointerGoingRight)
            {
                pointCoordX = pointCoordX - ballSpeed;
                pointerGoingLeft = true;
                pointerGoingRight = false;
            }
            else if (pointerGoingRight)
                pointCoordX = pointCoordX + ballSpeed;
            else
                pointCoordX = pointCoordX - ballSpeed;

            if(MyAnimationView.ballDropping == true)
            {
                while (pointCoordY<gregCoordY)
                    dropBall();
            }
    }

    public static void moveGreg(int x) {

        if (x <= 10 && goingLeft)
        {
        gregCoordX = gregCoordX + count;
        goingRight = true;
        goingLeft = false;
        }
        else if (x >= 410 && goingRight)
        {
        gregCoordX = gregCoordX - count;
        goingLeft = true;
        goingRight = false;
        }
        else if (goingRight)
        gregCoordX = gregCoordX + count;
        else
        gregCoordX = gregCoordX - count;
}

    @Override
    public void onClick(View arg0) {
        dropBall();
    }
}

MyAnimationView.java

package com.test.firstAnimation;

import android.content.Context;
import android.graphics.Canvas;
import android.view.View;

public class MyAnimationView extends View{

    private Sprite greg;
    private Sprite ball;
    private int xCoOr;
    private int ballXCoOr;
    public static boolean ballDropping;

    public MyAnimationView(Context context) {
        super(context);

        ballDropping = false;
        greg = new Sprite(context,R.drawable.greg);
        ball = new Sprite(context, R.drawable.ball);

        OnClickListener gregClicked = new OnClickListener() {
            public void onClick(View v) {
            ballDropping = true;
            }
        };
        greg.setOnClickListener(gregClicked);
        }

    @Override protected void onDraw(Canvas canvas) {

     canvas.drawColor(0xFFFFFFFF);                                   //white background      

     ballXCoOr = Sprite.getBX();  
     xCoOr = Sprite.getX();
     Sprite.moveGreg(xCoOr);                                         //move ball left or right depending
     Sprite.moveBall(ballXCoOr);

     if(ballDropping == true)
     {
         Sprite.dropBall();
     }

     canvas.drawBitmap(greg.getBitmap(), xCoOr, Sprite.getY(), null);
     canvas.drawBitmap(ball.getBitmap(), ballXCoOr, Sprite.getBY(), null);
     invalidate();
     }
}

提前致谢,我已经被困了好几天了!

最佳答案

    float touched_x, touched_y;
    boolean touched = false;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        touchCounter++;
        touched_x = event.getX();
        touched_y = event.getY();

        int action = event.getAction();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            touched = true;
            break;
        case MotionEvent.ACTION_MOVE:
            touched = true;
            break;
        case MotionEvent.ACTION_UP:
            touched = false;
            break;
        case MotionEvent.ACTION_CANCEL:
            touched = false;
            break;
        case MotionEvent.ACTION_OUTSIDE:
            touched = false;
            break;
        default:
        }
        return true; // processed
    }

然后;

    if (touched) {
        //control here
    }

touched_x, touched_y 是在屏幕上点击的点的坐标。你可以比较格雷格的坐标和这些坐标。如果相同,那么做你想做的。

关于java - 如何为 Android 自定义 View 添加 OnClick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7321642/

有关java - 如何为 Android 自定义 View 添加 OnClick 事件的更多相关文章

  1. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  2. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  3. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  4. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - 如何为 emacs 安装 ruby​​-mode - 2

    我刚刚为fedora安装了emacs。我想用emacs编写ruby。为ruby​​提供代码提示、代码完成类型功能所需的工具、扩展是什么? 最佳答案 ruby-mode已经包含在Emacs23之后的版本中。不过,它也可以通过ELPA获得。您可能感兴趣的其他一些事情是集成RVM、feature-mode(Cucumber)、rspec-mode、ruby-electric、inf-ruby、rinari(用于Rails)等。这是我当前用于Ruby开发的Emacs配置:https://github.com/citizen428/emacs

  8. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

随机推荐