Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Activity Dynamically

Tags:

android

I am working now on app, and I want to do the following:

  1. The user creates a new page (new activity and xml layout).
  2. Saving the user's page to database.
  3. 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!!!

like image 529
Josef Avatar asked Jul 16 '14 20:07

Josef


2 Answers

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.

like image 189
Gilad Haimov Avatar answered Sep 17 '22 19:09

Gilad Haimov


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

like image 31
Mobile Developer Avatar answered Sep 18 '22 19:09

Mobile Developer