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

时间:2012-05-07 16:23:33

标签: android

在android中,

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

我检查了clickListener和longclicklistener,但看起来他们并没有按我的意愿行事。

谢谢。

3 个答案:

答案 0 :(得分:2)

您可以使用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.
            */
        }
    }
}

答案 1 :(得分:0)

如果我是对的: 单击:用户按下并松开手指。 触摸:用户的手指仍在设备上。

也许您应该尝试使用onTouchListener? 我从来没用过它......

答案 2 :(得分:0)

使用OnTouchListener调用函数,直到用户按下按钮为止:

private OnTouchListener otl_conn = (OnTouchListener) new TouchListenerConn();
private Button bv = null;
bv = (Button) findViewById(R.id.xxxxbutton);
bv.setOnTouchListener(otl_conn);
 class  TouchListenerConn implements OnTouchListener  
    {
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
            //call function here
            break;
            case MotionEvent.ACTION_UP:
            //DO SOMETHING
            xxxx....;
            break;
            }
            return true;
        }
    }