获取当前时间毫秒在 Android onTouchListener 中始终相同

Getting current time millisecond is always same in Android onTouchListener

我正在开发一个 Android 应用程序。在我的应用程序中,我需要在 onTouchListener 中获取当前时间毫秒。我正在做的是当我触摸视图时,我以毫秒为单位记住那个时间,然后当触摸退出时,我计算第一次触摸和离开之间的时间差。

我的代码如下:

//about container is a linear layout
aboutContainer.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                long timeWhenDown = System.currentTimeMillis();
                if(event.getAction()==MotionEvent.ACTION_DOWN)
                {
                    timeWhenDown = System.currentTimeMillis();
                }

                if(event.getAction()==MotionEvent.ACTION_UP)
                {
                    Toast.makeText(getBaseContext(),String.valueOf(timeWhenDown) + " - " + String.valueOf(System.currentTimeMillis()),Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });

正如你在上面的代码中看到的,我记住了用户触摸布局的时间,然后吐司当前时间毫秒的值和用户触摸的时间。触摸在几秒钟后退出。但是当退出时,它正在烘烤与下面屏幕截图中相同的值。

为什么这两个值相同?实际上它应该是不同的,因为触地和触地时间不一样。我的代码有什么问题?怎样才能正确记住时间?

您需要将变量 timeWhenDown 声明为 ontouch 函数之外的全局变量,因为这样每个触摸事件 timeWhenDown 都会恢复为新值

public class MainActivity extends AppCompatActivity {

    View aboutContainer;
    long timeWhenDown;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        aboutContainer = (View)findViewById(R.id.aboutContainer);

        aboutContainer.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if(event.getAction () == MotionEvent.ACTION_DOWN)
                {
                    timeWhenDown = System.currentTimeMillis();
                }

               else if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    Toast.makeText(getBaseContext(),String.valueOf(timeWhenDown) + " - " + String.valueOf(System.currentTimeMillis()),Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

}

我测试了代码并且它工作正常。

您需要制作一个全局数组列表,并在动作上下添加毫秒,然后比较这两个值。