开发者

Slide finger into buttons android

How can I make 开发者_如何学Pythonit 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜