Start Another Activity from onCreate() in MainActvity?

后端 未结 5 524
终归单人心
终归单人心 2021-01-18 03:24

The problem I am having is that the onCreate() method within my MainActivity cannot seem to start another activity.

I have code working so that when I click a button

相关标签:
5条回答
  • 2021-01-18 03:30

    Your AboutActivity class...

    public class AboutActivity extends MainActivity {
    

    Please change it to:

    public class AboutActivity extends Activity {
    

    and as others noted, when constructing your intent, use this, or MainActivity.this.

    0 讨论(0)
  • 2021-01-18 03:31
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.activity_main);
    
    // Fire the intent that launches the "About" screen.
    Intent i= new Intent(this, AboutActivity.class);
    startActivity(i);
    
    0 讨论(0)
  • 2021-01-18 03:39

    I just realized what the problem is.

    The issue is that the AboutActivity is causing the intent to fire repeatedly. The first line in the AboutActivity's onCreate() is super.onCreate(savedInstanceState). This means that application control will go back to the MainActivity's onCreate() where the intent will then be fired again. Therefore, I seem to have caused an infinite loop of intent calling.

    I will post the solution if I find it.

    0 讨论(0)
  • 2021-01-18 03:47

    Try passing this instead of getBaseContext() to the intent.

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);
    
        // Fire the intent that launches the "About" screen.
        Intent aboutScreen = new Intent(this, AboutActivity.class);
        this.startActivity(aboutScreen);
    }
    
    0 讨论(0)
  • 2021-01-18 03:54

    Try this instead:

    Intent aboutScreen = new Intent(MainActivity.this, AboutActivity.class);
    this.startActivity(aboutScreen);
    
    0 讨论(0)
提交回复
热议问题