How to create Intent using a string to launch another activity?
The first activity in my app needs to load a small amount of data from a text file. Two strings and an integer.
Once I load the data, I wan开发者_如何转开发t to use one of the strings to create an intent, that will launch the next activity.
The current activity will not be able to have a hard-coded reference like so:
startActivity(new Intent(this, NextClass.class));
NextClass.class will need to be specified from a string in the file, and is included with the project.
I could create the data file in another activity, but I'm hoping to avoid creating another activity just for that when another way may be possible.
Try this:
try {
String className = 'com.www.tutorialforandroid.com.openActivity';
Intent openNewIntent = new Intent( this, Class.forName( className ) );
startActivity( openNewIntent );
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Are all the potential classes built into your project? If so, can't you just read the name of the string in your first activity and then translate the string to the actual class name (e.g. -
String className = getActivity(); //your reader for the string
if (className == "A") {
startActivity(new Intent(this, A.class));
}
else if (className == "B") {
startActivity(new Intent(this, B.class));
}
etc?
Starting arbitrary activities via component names is fragile, because it breaks encapsulation. If the other chunk of code gets refactored, all of a sudden your string will no longer be valid. Only do that within a single project, where any such refactorings will get picked up by the compiler.
Also, depending on where this file resides, there may be security issues.
Either use PackageManager
to find the activity via introspection, or have the file hold an action string and have the other activities set up Intent
filters to match.
精彩评论