如何在同一个动画图像视图中更改onTouchListener?

时间:2015-12-28 09:11:45

标签: java android ontouchlistener

就像某些应用程序中的那些传送带可以向右滑动(显示它),然后向左滑动以重新发送,再次隐藏它。我尝试在相同的视图上再次使用setOnTouchListener,并在它出现后显示延迟消息,但是当您尝试将其显示时,应用程序会收到错误并关闭(显示)。如果我要删除应该让它返回(隐藏)的方法,它会被带出来,但是如何让它发生,它可以被发送回来并通过向左滑动后隐藏它是通过向右滑动带出来的吗?

这是我在活动中使用的代码:

ImageView conveyorWheel;
private float x1, x2;
static final int MIN_DISTANCE = 150;
RelativeLayout parentLayout;
android.os.Handler conveyorHandler;

conveyorWheel = (ImageView) findViewById(R.id.conveyerWheel);
parentLayout = (RelativeLayout) findViewById(R.id.parentLayout);

protected void onCreate(Bundle savedInstanceState) {
...
 parentLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    x1 = event.getX();
                    break;

                case MotionEvent.ACTION_MOVE:
                    x2 = event.getX();
                    float deltaX = x2 - x1;
                    if (Math.abs(deltaX) > MIN_DISTANCE & x1 < x2) {

                        conveyorWheel.animate()
                                .x(-750)
                                .setDuration(150)
                                .start();

                        conveyorHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                conveyorRevert();
                            }
                        }, 151);

                        break;

                    }

                default:
                    return false;
            }
            return true;
        }
    });



}

private void conveyorRevert (){
    parentLayout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    x1 = event.getX();
                    break;

                case MotionEvent.ACTION_MOVE:
                    x2 = event.getX();
                    float deltaX = x2 - x1;
                    if (Math.abs(deltaX) > MIN_DISTANCE){

                        conveyorWheel.animate()
                                .x(-950)
                                .setDuration(150)
                                .start();

                        break;
                    }

                default: return false;
            }
            return true;
        }
    });
}

Android Monitor显示错误:  java.lang.NullPointerException:尝试调用虚方法&#39; boolean android.os.Handler.postDelayed(java.lang.Runnable,long)&#39;在空对象引用上

但我不知道如何解决这个问题

0 个答案:

没有答案