android – 当用户按下按钮直到用户释放该按钮时,如何调用函数重复


android中,

如何在用户按下按钮之前重复调用某个功能,直到他/她释放该按钮?

我检查了clickListener和longclicklistener,但看起来他们并不像我想要的那样.

谢谢.

最佳答案 您可以使用OnTouchListener:

public class MainActivity extends Activity implements OnTouchListener
{

    private Button button;

    // ...

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // ...

        button = (Button) findViewById(R.id.button_id);
        button.setOnTouchListener(this);

        // ...
    }

    // ...

    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        /* get a reference to the button that is being touched */
        Button b = (Button) v;

        /* get the action of the touch event */
        int action = event.getAction();

        if(action == MotionEvent.ACTION_DOWN)
        {
            /*
                A pressed gesture has started, the motion contains
                the initial starting location.
            */
        }
        else if(action == MotionEvent.ACTION_UP)
        {
            /*
                A pressed gesture has finished, the motion contains
                the final release location as well as any intermediate
                points since the last down or move event.
            */
        }
        else if(action == MotionEvent.ACTION_MOVE)
        {
            /*
                A change has happened during a press gesture (between
                ACTION_DOWN and ACTION_UP). The motion contains the
                most recent point, as well as any intermediate points
                since the last down or move event.
            */
        }
        else if(action == MotionEvent.ACTION_CANCEL)
        {
            /*
                The current gesture has been aborted. You will not
                receive any more points in it. You should treat this
                as an up event, but not perform any action that you
                normally would.
            */
        }
    }
}
点赞