繁体   English   中英

如何使用onTouchListener使按钮可触摸?

[英]How to make a button Touchable with onTouchListener?

我有一个试图使其可触摸的按钮,因此当我按住它时,它会在按住ImageView的时间内持续移动它,但是,每次按一下它只会移动ImageView一次。

final ImageView box = (ImageView) findViewById(R.id.box);
currentX = (int) box.getX();
Button rightarrow = (Button) findViewById(R.id.right);
rightarrow.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, final MotionEvent e) {
        v.performClick();
        if (e.getAction() == MotionEvent.ACTION_DOWN) {
            v.setPressed(true);
            handlerRight.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (e.getAction() == MotionEvent.ACTION_DOWN) {
                        currentX += 5;
                        box.setX(currentX);
                        handlerRight.postDelayed(this, 100);
                    } else {

                    }
                }
            }, 0);
        } else {
            v.setPressed(false);
        }
        return false;
    }
});

在您在那里运行的新线程中,需要创建一个while循环,该循环将在按下按钮时运行。 在该while循环中,只需移动图像即可。 这是代码:

final ImageView box = (ImageView) findViewById(R.id.box);
currentX = (int) box.getX();
Button rightarrow = (Button) findViewById(R.id.right);
rightarrow.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, final MotionEvent e) {
        v.performClick();
        if (e.getAction() == MotionEvent.ACTION_DOWN) {
            v.setPressed(true);
            handlerRight.postDelayed(new Runnable() {
                @Override
                public void run() {
                    while (v.isPressed()){
                        currentX += 5;
                        box.setX(currentX);
                        //handlerRight.postDelayed(this, 100);
                    }
                }
            }, 0);
        } else {
            v.setPressed(false);
        }
        return false;
    }
});

注意:我不确定

handlerRight.postDelayed(this, 100);

应该是因为我不熟悉它,所以您只需要把它放进去即可。 但这就是我希望的!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM