Android: How do you go to another activity on clic

2019-03-25 00:30发布

I'm trying to move onto the third activity in a sequence. Going from the main activity to the second one works fine but when I try to go to the third activity from the second I the application crashes.

Here's my code for the second activity:

package com.example.helloandroid;

import android.app.Activity;
//other imports here

public class Game extends Activity implements OnClickListener {

    private static final String TAG = "Matrix";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.matrix);
        View doneButton = findViewById(R.id.done_button);
        doneButton.setOnClickListener(this);
    }

    public void onClick(View v) { 
        switch (v.getId()) { 
            case R.id.done_button:
                Intent k = new Intent(this, GameTwo.class);
                startActivity(k);
                //finish();
                break;
        }
    }
}

And the code for the third activity:

package com.example.helloandroid;

import android.app.Activity;
//other imports here

public class GameTwo extends Activity {

   private static final String TAG = "Matrix";

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       this.setContentView(R.layout.matrixtwo);
       View donetwoButton = findViewById(R.id.donetwo_button);
   }
}

5条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-25 00:57
Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);

This works, but you also want to make sure that you specify this in your manifest.

查看更多
做自己的国王
3楼-- · 2019-03-25 01:03

Be sure to have the three Activities declared in the manifest. Is a common error to create the Activity and not declare it.

Call the new Activity using:

Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);
查看更多
相关推荐>>
4楼-- · 2019-03-25 01:10

It's a long shot but...
Your problem could also be caused by a NullPointerException
which is thrown if donetwo_button isn't declared in matrixtwo.xml...
(Copy-paste errors are quite common)

查看更多
一夜七次
5楼-- · 2019-03-25 01:13

Try the following code in the switch:

try {
    Intent k = new Intent(Game.this, GameTwo.class);
    startActivity(k);
} catch(Exception e) {
    e.printStackTrace();
}

Tell me is this helpful.....

查看更多
The star\"
6楼-- · 2019-03-25 01:15

Try this

Intent intent = new Intent(getApplicationContext(), GameTwo.class);
startActivity(intent);
查看更多
登录 后发表回答