Starting an Activity with Intent and SetClassName

前端 未结 2 1269
太阳男子
太阳男子 2021-01-25 01:13

I am using the following code to move to another Activity :

Intent intent = new Intent();  
String test = \"Navigate\";  
intent.setClassName(this.context,test         


        
相关标签:
2条回答
  • 2021-01-25 01:18

    You need the full classname, including the package:

    String test = "your.package.here.Navigate";
    

    (And the Activity defined in the Manifest, but as you can start it with Navigate.class I assume you have already done this).

    0 讨论(0)
  • 2021-01-25 01:36

    I would use the more explicit constructor: Intent (Context packageContext, Class<?> cls). From the docs:

    [...] This provides a convenient way to create an intent that is intended to execute a hard-coded class name, rather than relying on the system to find an appropriate class for you [...]

    This constructor internally calls the setComponent()-method, which is also called by your used setClassName()-method. But using the constructor spares you code-lines and makes the code more readable:

    Intent i = new Intent(this, Navigate.class);
    intent.putExtra("params", params);
    this.startActivity(i);
    

    Note that using this only works this way, when in an Activity, because the activity-class extends the Context-class.

    Another advantage over hard-coding the package and class-names as a String is, that when you move a class to another package (or rename a package), you'll get compile-time errors, not runtime-errors.

    Also, for this to work, you'll need to register the Activity in the Android Manifest.

    0 讨论(0)
提交回复
热议问题