gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:09:40 25 4
gpt4 key购买 nike

您好,我是一名大学生,具有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com