Creating Activity Dynamically

Indeed there is no way for dynamically creating new activities.

But you can create multiple instances of the same activity. This will require setting your activity's launchMode to "standard" or "singleTop" .

Additionally, you may use initialization flags to have each of these instances use its own specific layout, creating a user experience which is literally identical as having multiple activities:

Intent intent = new Intent(this, MyDynamicActivity.class);
Bundle b = new Bundle();
b.putInt("LayoutIndex", mode);
intent.putExtras(b);
startActivity(intent);

And the activity:

class MyDynamicActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState)  {
         super.onCreate(savedInstanceState);

         Bundle b = getIntent().getExtras();
         int layoutIndex = b.getInt("LayoutIndex");
         // and here populate the activity differently based on layoutIndex value
    }

}

But how can you dynamically populate different instances of an activity?

Well, there is no easy way. You cannot for example create an ad-hoc XML layout file and store it in filesystem, because XML layouts must be compiled in a specific format to be loadable by Android.

The only thing you can do is from your Java code dynamically set the layout widgets following the rules set by the user. Below is an example of how Java layout generation code looks like:

LinearLayout layout = new LinearLayout(this);
layout.setGravity(Gravity.CENTER);

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setText("My Button");
layout.addView(button, params); 

setContentView(layout);

Have no doubt, creating such a dynamic mechanism will be a lot of work.


Perhaps instead of an Activity you could use Dialog or PopupWindow?

Tags:

Android