Can I send the class as optional with the intention?

I am trying to pass the class name additionally, how to do this?

Intent p = new Intent(StartScreen.this, Setting.class); p.putExtra(" ",StartScreen.this); 

I want to get the class name in the Setting class, but I don't want it to be String , because I'm going to use this class name as follows:

 Bundle extras = getIntent().getExtras(); extras.getString("class"); Intent i = new Intent(Setting.this, class); startActivity(i); 
+7
source share
2 answers

you can use this code

 Intent p = new Intent(StartScreen.this, Setting.class); p.putExtra("class","packagename.classname"); 

and when setting the class

 Bundle extras = getIntent().getExtras(); String classname=extras.getString("class"); Class<?> clazz = Class.forName(classname); Intent i = new Intent(Setting.this, clazz); startActivity(i); 
+15
source

A more subtle way than the accepted answer would be to use Serializable or Parcelable .

Here is an example of how to do this using Serializable :

In your first action ...

 Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("EXTRA_NEXT_ACTIVITY_CLASS", ThirdActivity.class); startActivity(intent); 

Then in your second action ...

 Bundle extras = getIntent().getExtras(); Class nextActivityClass = (Class<Activity>)extras.getSerializable("EXTRA_NEXT_ACTIVITY_CLASS"); Intent intent = new Intent(SecondActivity.this, nextActivityClass); startActivity(intent); 

Doing this with Parcelable pretty much the same, except that you replaced extras.getSerializable("EXTRA_NEXT_ACTIVITY_CLASS") in the above code with extras.getParcelable("EXTRA_NEXT_ACTIVITY_CLASS") .

The Parcelable method will be faster, but harder to set up (for how you need to make your third Activity Parcelable - see http://developer.android.com/reference/android/os/Parcelable.html ).

+7
source

All Articles