Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which view your finger is sliding over in Android

While similar questions have been asked in the past they don't seem to really have been answered which might be due to confusion as to what's being asked.

Put simply, I'd like to detect which view is being entered as your finger slides over the screen. The best example of this in action is the soft keyboard on any android phone. When you press any key it shows up as a popup to tell you what letter is under your finger. If you now move your finger over the keyboard in a single gesture the various letters pop up as you move over the various letters of the alphabet.

What listeners are used for this type of behaviour. I've tried OnTouchListeners but they seem to be only when you 'touch' the button as opposed to 'finger past' them

Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {doStuff();}
});

button.setOnTouchListener(new OnTouchListener() {
  @Override
  public boolean onTouch(View v, MotionEvent event) {
      doStuff();
      return false;
  }
});

OnFocusChangeListener don't help either.

like image 570
Tim Avatar asked Jan 29 '11 18:01

Tim


1 Answers

  • create a Layout
  • add Views to your Layout
  • set the setOnTouchListener to your Layout
  • override the onTouch method with the following:

    public boolean onTouch(View v, MotionEvent event) 
    {
       LinearLayout layout = (LinearLayout)v;
    
        for(int i =0; i< layout.getChildCount(); i++)
        {
    
            View view = layout.getChildAt(i);
            Rect outRect = new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
            if(outRect.contains((int)event.getX(), (int)event.getY()))
            {
                                 // over a View
            }
        }
    }
    
like image 56
Garry Avatar answered Oct 12 '22 14:10

Garry