I am working now on app, and I want to do the following:
- The user creates a new page (new activity and xml layout).
- Saving the user's page to database.
- Adding the page to ListView as an item, and launch it when the user
will click it on the ListView.
I saw many answers here about "Creating Activity Dynamically" and I understand it's impossible, so i don't know how to do that.
The number of the pages the user can create is unlimited so it must be done dynamically. Each layout of a page in the ListView is the same.
Thank you very much!!!
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With