如何知道哪些被触摸视图 [英] How to know which View is being touched

查看:190
本文介绍了如何知道哪些被触摸视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个乒乓游戏,该桨在屏幕底部显示和砖头放在最上面。我用三个观点,一个是桨,一个球,另外一个是描绘了两个视图(球和桨)主要观点:

I'm trying to build a Ping Pong game, that the paddle is shown in the bottom of the screen and the bricks is on the top. I use three views, one for the paddle, one for the ball and another one that is the main view that paints the two views (ball and paddle):

public void draw(Canvas canvas){
    BallView.draw(canvas);
    PaddleView.draw(canvas);
}

我想知道的是,如果我能确定哪些观点被触摸正好,我尝试用 onTouchEvent 来做到这一点的主要活动:

What I want to know is if I can identify which view is being touched exactly, I try to do it with onTouchEvent in the main Activity:

   @Override
    public boolean onTouchEvent(MotionEvent event){
        Log.d("touched", "touched")
        return true;
    }

不过,问题是,不管我在哪里触摸屏幕上,桨移动,我想,只有当我触摸桨,他会移动。
所以,我怎么能做到这一点,如果可能的话?
谢谢你。

But, the problem is that no matter where I touch on the screen, the paddle is moving, and I want, that only when I touch the Paddle he will move. SO, how can I do this, if it is possible? Thanks.

推荐答案

您可以用另一种方式一样做到这一点,就画两个相对的布局,蓝色和黄色相同的情况下,使之既相对布局为一个可点击:真从XML和处理的onClick:onClickHandler。希望这会为你工作。

You can achieve this in another way like, just draw two relative layouts blue and yellow same as in your case and make it both relative layout as a clickable : true from the xml and handle the onClick:"onClickHandler". hope this will work for you.

                <RelativeLayout
                    android:id="@+id/rl_click_blue"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentRight="true"
                    android:background="#ffffff"
                    android:clickable="true"
                    android:onClick="onClickHandler">
                </RelativeLayout> 

                <RelativeLayout
                    android:id="@+id/rl_click_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentRight="true"
                    android:background="#ffffff"
                    android:clickable="true"
                    android:onClick="onClickHandler">
                </RelativeLayout> 

               // Handle your functionality here.
               public void onClickHandler(View v)
               {
                   switch (v.getId()) {
                       case R.id.rl_click_blue:
                           break;

                       case R.id.rl_click_yellow:

                          break;
                   }
               }

这篇关于如何知道哪些被触摸视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆