2017-09-11 11 views
1

こんにちは私は仕事のためのサイドプロジェクトとしてこのアプリを作るhtmlとJavaScriptの背景を持つ大学生です。私は、ボタンを押して早くカウントダウンタイマーを終了すると同時に、ユーザーを別のアクティビティに連れて行くのを助けたいと思います。私は私のコードをアセンブルするために2つの異なるガイドを使用して、私はタイマーを働いている。ハンドラを終了し、ボタンでアクティビティを変更するにはどうすればいいですか?

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

答えて

0

グローバルハンドラを宣言し、どこにでも使用する必要があります。ハンドラで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); 
    } 
    }); 
} 
+0

この回答ありがとうございます、それは私のために働いた。 – INFJx386

0

あなたがポストをキャンセルするのsendMessage + removeMessageを使用することができますが、あなたはすぐにそれを実行カント:私はここに私のコードですので、任意のヘルプは歓迎されるだろうジャワの限られた知識を持っています。

Handler h = new Handler() { 
public void handleMessage(int what){ 
    Intent i = new Intent(Main2Activity.this, MainActivity.class); 
    startActivity(i); 
    finish(); 
} 
} 
h.sendEmptyMessageDelayed(111, TIME_OUT); 
//On your button Listener 
h.removeMessages(111); 

このようにして、メッセージはキャンセルされ、タイムアウトでは起動されません。

+0

私は自分のコードでどのように使用しますか? – INFJx386

+0

アップデートを確認してください。実装からコードを削除しました。 –

関連する問題