Android: Dynamically Starting An Activity
I would like to dynamically start an activity based on the previous activity's input. I have input a string through the previous activity, the only thing is this specific code thro
Solution 1:
The ComponentName object does just that:
Stringactivity= intent.getStringExtra(MainActivity.TEST_TYPE);
Intentintent=newIntent(this, newComponentName(this, activity));
startActivity(intent);
That's assuming this
is an instance of Activity
. (for a Fragment
, use getActivity()
, obv.)
Solution 2:
I have a class on here:
com.yasinkacmaz.newproject.activity.ProfileActivity
My test string like that:
"com.yasinkacmaz.newproject.activity.ProfileActivity"
And it working good:
publicclassEasyCountDownextendsAppCompatActivity {
finalActivitythisActivity=this;
private Intent previousIntent,nextIntent;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
previousIntent = getIntent();
Stringtest= previousIntent.getStringExtra(MainActivity.TEST_TYPE);
finalStringactivity= test;
Classnewclass=null;
try {
newclass = Class.forName(activity);
} catch (ClassNotFoundException c) {
c.printStackTrace();
}
if(newclasss != null) {
nextIntent = newIntent(thisActivity, newclass);
startActivity(nextIntent);
} else {
Toast.makeText(getApplicationContext(),"new class null",Toast.LENGTH_SHORT).show();
}
}
}
Dont forget you can use switch case or etc., because in this way you can get ClassNotFoundException
and your intent will be null
.
Post a Comment for "Android: Dynamically Starting An Activity"