Search code examples
androidontouchlistener

Getting current time millisecond is always same in Android onTouchListener


I am developing an Android App. In my app, I need to get current time millisecond in onTouchListener. What I am doing is when I touch on the view, I memorize that time in millisecond, then when touch exit, I calculate the time difference between first touch and leave.

My code is below:

//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;
            }
        });

As you can see in the code above, I memorize the time when user touch on layout, then toast the value of current time milliseconds and the time when user touched in. Touch exits after a few seconds. But when exit, it is toasting same value as in the below screenshot.

enter image description here

Why are these two values same? Actually it should be different since touch down and touch up time are not same. What is wrong with my code? How can I correctly memorize the time?


Solution

  • You need to declare the variable timeWhenDown as a global variable out side the ontouch function, because this way every touch event timeWhenDown is rested to the new value

    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;
                }
            });
        }
    
    }
    

    I tested the code and its working fine.