繁体   English   中英

onCreate被调用两次

[英]onCreate is called twice

我有2个活动-MainActivity和page1。 我有这样的意图:

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

但是,我的Page1类的onCreate被调用了两次! 我可以用吐司消息检测到它:它在屏幕上出现两次:

@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...
}
        });`

我确实有一些在Page1活动中使用countdowntimer的方法,等待2秒的计时器,我已将它们注释掉,但是onCreate()仍然被调用两次。

我添加了代码以防止屏幕旋转,但是错误仍然存​​在

问题在于您的触摸监听器不会检查我们拥有的事件类型,这意味着您的onTouch应该每秒被调用100次,但实际上只被调用了两次,因为新的Activity UI覆盖了按钮。 使用此代码检查我们发生的事件:

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

如果动作为ACTION_DOWN则表示用户刚刚触摸了按钮。 如果是ACTION_UP则表示用户举起了手指。

暂无
暂无

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

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