简体   繁体   English

onCreate被调用两次

[英]onCreate is called twice

I have 2 activities - MainActivity and page1. 我有2个活动-MainActivity和page1。 I have intent from the first like this: 我有这样的意图:

 button_forward.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Intent intent = new Intent(MainActivity.this, Page1.class);
                startActivity(intent);
                return true ;
            }

However, my Page1 class's onCreate is called twice! 但是,我的Page1类的onCreate被调用了两次! i can detect it with toast message: it appears twice on the screen: 我可以用吐司消息检测到它:它在屏幕上出现两次:

@Override
protected void onCreate(Bundle savedInstanceState) {

    Toast.makeText(Page1.this, "onCreate 1", Toast.LENGTH_SHORT).show();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.page1);
    //some code here like findview by id...
}
        });`

I do have some methods that use countdowntimer in my Page1 activity, timers that wait for 2 secs, i commented them out, but onCreate() still gets called twice. 我确实有一些在Page1活动中使用countdowntimer的方法,等待2秒的计时器,我已将它们注释掉,但是onCreate()仍然被调用两次。

I added code to prevent screen rotating, but the error persists 我添加了代码以防止屏幕旋转,但是错误仍然存​​在

The problem is that your touch listener doesn't check which type of event we have, this means that your onTouch should be called like 100 times per second, but it actually is called only twice because the new Activity UI covers the button. 问题在于您的触摸监听器不会检查我们拥有的事件类型,这意味着您的onTouch应该每秒被调用100次,但实际上只被调用了两次,因为新的Activity UI覆盖了按钮。 Use this code to check which event we have: 使用此代码检查我们发生的事件:

@Override
public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() != MotionEvent.ACTION_DOWN) return false;
    Intent intent = new Intent(MainActivity.this, Page1.class);
    startActivity(intent);
    return true;
}

If the action is ACTION_DOWN it means that the user has just touched the button. 如果动作为ACTION_DOWN则表示用户刚刚触摸了按钮。 If it is ACTION_UP it means that the user lifted his / her finger. 如果是ACTION_UP则表示用户举起了手指。

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

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