简体   繁体   English

按下返回按钮3秒钟

[英]3 seconds for pressing the back button

I tried to write an app, in which first user see splashcreen and after 3 seconds he is moved to mainscreen. 我尝试编写一个应用程序,在该应用程序中,第一个用户看到了飞溅螺丝,并在3秒钟后将其移至主屏幕。 If user press back button during this 3 seconds, he will stay on splashscreen 如果用户在这3秒钟内按下返回按钮,他将停留在初始屏幕上

I tried few methods of delay ( like stopping the thread or some stupid for loop) but i couldn't do my task ( changing screen after 3 sec and not if back was pressed) 我尝试了几种延迟方法(例如停止线程或某些愚蠢的for循环),但是我无法完成任务(3秒后更改屏幕,如果按下后退则不行)

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;

import java.util.concurrent.TimeUnit;


public class MainActivity extends AppCompatActivity {

    boolean checkerbool=true;// check if its in the 3s loop
    boolean background=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen);
         Handler handler=new Handler();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                checkerbool=false;
            }
            }, 3000);
      if(background) setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(checkerbool) background=false;

            return true;
        }


        return super.onKeyDown(keyCode, event);
    }
}

But after starting an app it jumps directly into mainscreen Working project will be when user is moved to diffrent screen after 3s and if user press the button back, he will stay at splashscreen 但是启动应用程序后,它会直接跳入主屏幕。工作项目将是3秒钟后用户移至其他屏幕,如果用户向后按按钮,他将停留在启动屏幕上

override the onBackPressed method : 覆盖onBackPressed方法:

@Override
public void onBackPressed() {
    checkerbool = true;
}

Change : 变更:

boolean checkerbool=false;

Finally : 最后:

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        if(!checkerbool)
            setContentView(R.layout.activity_main);
    }
 }, 3000);

You need to move setContent to the run method, because postDelayed will no block the main thread it just post execute what is inside run after the time you mention(3000). 您需要将setContent移到run方法,因为postDelayed不会阻塞主线程,它只会在您提到(3000)之后发布内部run

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

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