2

How can I make it possible that when someone slides their finger into or over a button, the button acts as if it were getting pushed?

An example of what i'm looking for would be a keyboard app. Where you slide your fingers over all the keys to play sounds.

Sam
  • 864
  • 7
  • 15

1 Answers1

0

You can use an OnTouchListener like this:

    boolean firstTime = true;
    OnTouchListener testTouchListener = new OnTouchListener(){
        public boolean onTouch(View v, MotionEvent me){
            Rect r = new Rect();
            secondButton.getDrawingRect(r);
            if(r.contains((int)me.getX(),(int)me.getY())){
                //Log.i(myTag, "Moved to button 2");
                if(firstTime == true){
                    firstTime = false;
                    secondButton.performClick();
                }
            }
            if(me.getAction() == MotionEvent.ACTION_UP){
                //When we lift finger reset the firstTime flag
                firstTime = true;
            }
            return false;

        }
    };
    firstButton.setOnTouchListener(testTouchListener);

With this approach though you are going to get a flood of touch events because onTouch() gets called a lot with MotionEvent.ACTION_MOVE. So you'll have to keep a boolean that tells you if its the first time you've gotten onTouch() call. Then you can reset that boolean in onTouch() for MotionEvent.ACTION_UP so it works again the next time. However this could get kind of complicated if you are trying to do more than just 2 buttons. I think you'd have to keep a boolean for each of them seperately (or perhaps an array of booleans to hold them all). and you'd need an additional if(r.contains(x,y) statements for every button. This should get you started on the right path though.

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • Thanks that worked great, but how can I getDrawingRect from a button that uses android:layout_weight ? – Sam Feb 22 '11 at 19:38
  • I generally don't use the layout_weight parameter in my layouts so I am not experienced with it really. But I wouldn't think that it would affect the getDrawingRect() method. My understanding of it is that as long as the view is on the screen(on the layout passed to setContentView()) then it will return a Rect object representing the size on the screen that it takes up. – FoamyGuy Feb 22 '11 at 21:00