简体   繁体   English

Android 中的 onTouchEvent()

[英]onTouchEvent() in Android

I am new to Android development.我是 Android 开发的新手。

How to write onTouchEvent() in one activity and access in all other activities in the application?如何在一个活动中编写onTouchEvent()并在应用程序中的所有其他活动中访问?

I am trying in following way:我正在尝试以下方式:

Public class TouchActivity extends Activity
{
    @Override
    public boolean onTouchEvent(MotionEvent event){

        int action = MotionEventCompat.getActionMasked(event);
        boolean touch_up_detect;
        if (action == MotionEvent.ACTION_UP)
        {
            //touch_up_detect = true;
            if (timer == null)
            {
                timer = new Timer();
                timer.schedule(new ScheduledTaskWithHandeler(), 10000);
            }               
        }
        else if (action == MotionEvent.ACTION_DOWN)
        {
            System.out.println("user touching screen**********");
            if (timer != null)
            {
                timer.cancel();
                timer.purge();
            }                 
        }
        return false;           
    }
    class ScheduledTaskWithHandeler extends TimerTask {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Intent intent = new Intent(TouchActivty.this, MainActivity.class);
            startActivity(intent);

        }   
    }
}

public class DashboardActivity extends TouchActivity
{

}

Whenever I am touching the dashboard activity, I am not able to access onTouchEvent() from TouchActivity .每当我触摸仪表板活动时,我都无法从TouchActivity访问onTouchEvent()

That is because you are extending the activity with DashboardActivity.那是因为您正在使用 DashboardActivity 扩展活动。 This means that, as far as your device is concerned, these are two separate functions.这意味着,就您的设备而言,这是两个独立的功能。 Activities are roughly separate beasts that are independent from one another.活动大致是彼此独立的独立野兽。

If you just want to manipulate the timer in your Touch Activity, you could start an activity for result and pass the timer in as an argument.如果您只想在 Touch Activity 中操作计时器,您可以启动一个结果活动并将计时器作为参数传入。 I think this will achieve what you are asking for.我认为这将实现您的要求。 Here you can find a question which talks about passing data between activities. 在这里你可以找到一个关于在活动之间传递数据的问题。

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

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