java - 如何使用按钮结束处理程序并更改 Activity ?

标签 java android

您好,我是一名大学生,具有 html 和 JavaScript 背景,使这个应用程序作为工作的副项目。我希望通过按下按钮提前结束倒计时,同时将用户带到另一项 Activity 。我使用了两种不同的指南来组装我的代码,并且计时器正在工作。我对java的了解有限,所以欢迎任何帮助,这是我的代码:

public class Main2Activity extends AppCompatActivity {

    Button button1;

    int flag=0;

    // page should show up for 2 seconds then take you to the main page, but I want a button there to stop the count down and take the user to a different page That I will use as a credits page

    private static int TIME_OUT = 2000; //Time to launch the another activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(Main2Activity.this, MainActivity.class); //Main2Activity is the Welcome page and MainActivity is the home page
                startActivity(i);
                finish();

            }

        }, TIME_OUT);
        button1 = (Button) findViewById(R.id.credit);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                flag = 1;
                Handler.removeCallbacksAndMessages(null);
                Intent intent = new Intent(Main2Activity.this, credit.class);
                startActivity(intent);
            }
        });
    }
}

最佳答案

您应该声明一个全局处理程序并在任何地方使用它。不要在处理程序中使用final

Handler handler;
private static int TIME_OUT = 2000; //Time to launch the another activity

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
handler = new Handler();

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent i = new Intent(Main2Activity.this, MainActivity.class); //Main2Activity is the Welcome page and MainActivity is the home page
        startActivity(i);
        finish();

    }

}, TIME_OUT);
button1 = (Button) findViewById(R.id.credit);
button1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        flag = 1;
        handler.removeCallbacksAndMessages(null);
        Intent intent = new Intent(Main2Activity.this, credit.class);
        startActivity(intent);
    }
  });
}

关于java - 如何使用按钮结束处理程序并更改 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46159929/

相关文章:

android - 如何使用Delphi XE5在IOS上保存位图图片

java - 在 android 中为 fragment 创建 "Shell"

java - 如何从文件中读取由返回分隔的字符串

获取 SOAP 响应时出现 javax.xml.bind.UnmarshalException

android - Android map 中的自定义图案项

android - 如何计算与设备无关的像素单元?

android - 播放按钮点击的音效 (CLICK/NAVIGATION_RIGHT) - Android

java - PropertyPlaceholder 不够用的 Spring 每个环境配置

java - 泛型继承有什么问题

java - 为什么我的 Controller 没有与我的存储库连接