Android - change fragment format at runtime

I would like to implement the Single-Activity Multi-Fragments project in my application. I plan to have several β€œscreens” (Fragment layouts) that I will switch between (possibly adding to the back-stack) in the code.

As I understand it, the location of the fragments on each screen is set using Layout objects (for example, FrameLayout), which act as placeholders for the fragments (share the same identifier). Since there are different fragmentation mechanisms on different screens (maybe FrameLayout and another LinearLayout, etc.) I was wondering: how do I switch between fragment layouts at runtime?

I understand adding / replacing fragments (via the FragmentManager), but I would like to completely add a new layout containing them in live activity. A kind of like transaction for "setContentView" ...

How can I do it? Thank you Danny

+8
android android-layout android-fragments
source share
1 answer

Of course, perhaps you only need to create your own identifiers. Identifiers can be any, but they should not conflict with aapt identifiers (those specified in R) and should not be negative.

The following example demonstrates this with a set of fixed identifiers:

public class MainActivity extends Activity { private final int ID_TABLE = 0xA; private final int ID_ROW1 = 0xB; private final int ID_ROW2 = 0xC; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout ll = (LinearLayout) findViewById(R.id.root); TableLayout tl = new TableLayout(this); tl.setId(ID_TABLE); TableRow tr1 = new TableRow(this); tr1.setId(ID_ROW1); TableRow tr2 = new TableRow(this); tr2.setId(ID_ROW2); tl.addView(tr1); tl.addView(tr2); ll.addView(tl); MyFragment frag1 = new MyFragment(); MyFragment frag2 = new MyFragment(); MyFragment frag3 = new MyFragment(); MyFragment frag4 = new MyFragment(); getFragmentManager().beginTransaction() .add(ID_ROW1, frag1, "cell1_1") .add(ID_ROW1, frag2, "cell1_2") .add(ID_ROW2, frag3, "cell2_1") .add(ID_ROW2, frag4, "cell2_2") .commit(); getFragmentManager().executePendingTransactions(); } } 

To switch to another layout, you can delete fragments and add them to another location.
Let me know how this happens.

EDIT: for clarification, views and groups of views should not be created once, and then stored throughout the life of the Activity. Just make sure any fragments are removed or disconnected before deleting their associated view. In addition, if you create and delete views outside of onCreate, you must make sure that they can be restored using onSaveInstanceState and repeat the process in onCreate. Read the diagram here and the configuration change point.

+4
source share

All Articles