Get the co-ordinates of a touch event on Android

前端 未结 4 569
眼角桃花
眼角桃花 2020-11-30 04:26

I\'m new to Android, I\'ve followed the hello world tutorial through and have a basic idea of what\'s going on. I\'m particularly interested in the touch screen of my T-Mob

4条回答
  •  情书的邮戳
    2020-11-30 04:47

    You can use this function : http://developer.android.com/reference/android/view/View.html#setOnTouchListener(android.view.View.OnTouchListener)

    You will probably put it in your onCreate method roughly this way (tested this time) :

    Activity onCreate code

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView textView = (TextView)findViewById(R.id.textView);
        // this is the view on which you will listen for touch events
        final View touchView = findViewById(R.id.touchView);
        touchView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                textView.setText("Touch coordinates : " +
                    String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
                    return true;
            }
        });
    }
    

    layout code

                                          
    
    
    
    
    

    Edit: I tried my code and indeed there were a few errors. Anyway, with the layout I give you here it works on my emulator. Can you provide maybe more code/context so I can see what's wrong?

提交回复
热议问题