如何为 Android 自定义视图添加 OnClick 事件

2023-11-26

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

我的问题是我似乎无法添加 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));
       }
    }

雪碧图.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();
     }
}

预先感谢,我已经被困了好几天了!

Ben


    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
    }

Then;

    if (touched) {
        //control here
    }

Touched_x、Touched_y 是屏幕上单击的点的坐标。您可以比较格雷格的坐标和这些坐标。如果一样,那就做你想做的事吧。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 Android 自定义视图添加 OnClick 事件 的相关文章

  • Android 将菜单项在操作栏中向左对齐

    我的应用程序中有一个操作栏 它显示我定义的菜单项res menu activity main xml 我的菜单项在操作栏上向右对齐 我希望它们左对齐 我为此找到的唯一解决方案使用了自定义操作栏 如下所示 将菜单项放置在 Honeycomb
  • splitByWholeSeparatorPreserveAllTokens 和 split 之间的区别

    有什么区别StringUtils splitByWholeSeparatorPreserveAllTokens and String split With splitByWholeSeparatorPreserveAllTokens 我们可
  • 嵌套枚举是静态的吗?

    读书时这个问题 https stackoverflow com questions 25011061 why can enum implementations not access private fields in the enum cl
  • Log4j 未使用属性文件找到自定义附加程序

    我正在尝试使用以下 XML 属性文件在 Eclipse 插件项目中配置 log4j 其中包括一个名为 EclipseLoggingAppender 的自定义附加程序
  • 为什么这不会导致 NullPointerException?

    public class Null public static void greet System out println Hello world public static void main String args Null null
  • 找不到资源矢量绘图的异常

    我将在某些设备上运行我的应用程序 其崩溃日志如下 01 04 16 54 02 206 7466 7466 com lawnmowers E AndroidRuntime FATAL EXCEPTION main Process com l
  • 使用java读取Excel工作表的单列

    我有一张 Excel 表格 我想编写一个方法 该方法将参数作为要读取的列号 并返回一个由该列中的所有数据组成的数组 然后将该列元素放置在 xml 工作表中 我怎样才能编写一个方法来做到这一点 使用 Apache POI 您可以在他们的使用页
  • 当另一个线程发生事情时从主线程获取数据?

    目前我有一个线程正在运行一个侦听连接的套接字 当它收到连接时 它需要上传在主线程中收集的数据 即从主线程获取数据 但是 我传递了对象的实例 但它从未使用等待连接时收集的数据进行更新 有没有正确的方法来做到这一点 我用谷歌搜索了一下 似乎找不
  • Android 视图和视图组

    在安卓中ViewGroup继承自View A ViewGroup是一个容器 里面装有Views ViewGroup LinearLayout View TextView 为什么 Android 的人们将这种关系定义为Inheritance而
  • 我们可以用java定制一个垃圾收集器吗?

    我们知道java的垃圾收集器是一个低优先级线程 在java中我们可以创建任何具有高优先级的线程 那么是否有可能拥有我们自己定制的具有可变优先级的垃圾收集器线程 我们可以根据内存管理的级别进行设置 有人尝试过吗 如果是的话 您能分享一些关于如
  • 如何在jpa中共享EntityManagerFactory

    我是 jpa 的新手 这是场景 我正在开发一个 Web 应用程序 其中 多个用户可以登录 当 user1 注销时 我正在使用下面的代码 public static void closeEntityManagerFactory if enti
  • 如何用 XML 制作双渐变(类似 iphone)

    如何使用 XML 制作这种可绘制渐变 我可以做一个从颜色 A 到颜色 B 的简单渐变 但我不知道如何在同一个可绘制对象中组合两个渐变 我终于找到了一个带有图层列表的解决方案 这对我来说已经足够好了
  • Admob - 没有广告可显示

    你好 我尝试制作一些在 Android 手机上显示广告的示例程序 并尝试在 v2 2 的模拟器上测试它 代码中的一切似乎都很好 但调试器中的 AdListener 表示 响应消息为零或空 onFailedToReceiveAd 没有广告可显
  • 如何手动添加Android Studio依赖

    我多次尝试向我的项目添加依赖项 但每次都会出现错误 我想添加它们的依赖项是 de hdodenhof circleimageview 1 3 0 and com github bumptech glide glide 3 6 1 所以我想下
  • 用于从链表中删除元素的大 O 表示法[重复]

    这个问题在这里已经有答案了 我正在阅读有关链接列表的内容 我发现 从链表中删除所需的元素需要 O n 运行时间 其中 n 是元素的数量 列表中的元素 http www cs mcgill ca dprecup courses IntroCS
  • TYPE_ACCELEROMETER 和 TYPE_LINEAR_ACCELERATION 传感器有什么区别?

    I think TYPE ACCELEROMETER显示设备加速 但是 我不明白什么时候应该使用TYPE LINEAR ACCELERATION 我需要计算移动设备的速度 哪种传感器适合此应用 另外 我读到TYPE LINEAR ACCEL
  • 在测试期间调用预定方法[重复]

    这个问题在这里已经有答案了 我正在使用 Maven 开发 SpringBoot 应用程序 我有一个班级 Component有方法的注释m与 Scheduled initialDelay 1000 fixedDelay 5000 注解 这里f
  • RecyclerView元素更新+异步网络调用

    我有一个按预期工作的回收视图 我的布局中有一个按钮可以填充列表 该按钮应该进行异步调用 根据结果 我更改按钮的外观 这一切都发生得很好 但是 当我单击按钮并快速向下滚动列表时 异步调用的结果会更新新视图的按钮 代替旧视图的视图 我该如何处理
  • 在 Vavr 中结合任一者?

    我有几个Vavr https www vavr io Either https www vavr io vavr docs either的 我想调用一个函数Right每个 Either 的值 例如 Either
  • Java applet 是否会违反同源策略

    我需要请求一些东西并从其他域获取信息 我知道由于同源政策 javascript 无法做到这一点 我的另一个选择是通过我的服务器发出代理请求 我不希望请求来自我的服务器的 IP 也不想为我的服务器创建额外的负载 并且希望客户端这样做 是否可以

随机推荐