Cel
Cel

Reputation: 6659

Add fragments before main activity shows main content view

Splash

I have main activity UI startup operations that take between 5-10 seconds (that need to be handled on the main UI thread) - so I would like to use a splash screen rather than the default black or non-responsive main UI.

A good solution to the splash screen is provided below

Android Splash Screen before black screen


Splash with Fragments

I'm also using fragments, which normally require setContentView(R.layout.main) to be called before fragment instantiation - so that the fragment manager could find the view stubs in R.layout.main to inflate the fragments into (strictly speaking view stubs are a different thing).


Almost-Answer

Here's all but the key, which is that setContentView is called before the fragment transactions: How do I add a Fragment to an Activity with a programmatically created content view

Upvotes: 2

Views: 4748

Answers (2)

mrcaramori
mrcaramori

Reputation: 2503

You could try replacing your fragments in your FragmentActivity, here is the idea partially coded: Suppose you have your fragments layout like this (main.xml):

<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">

    <LinearLayout android:id="@+id/waiting" ...>
    </LinearLayout>

    <!-- hidden layout -->
    <LinearLayout>
        <LinearLayout android:id="@+id/layout_list_items" ...>
        </LinearLayout>
        <LinearLayout android:id="@+id/layout_detail" ...>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

And your FragmentActivity like this:

public class FragmentsActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);

        Fragment fragA = new WaitingTransaction();

        FragmentTransaction fragTrans = this.getSupportFragmentManager().beginTransaction();
        fragTrans.add(R.main.waiting, fragA);
        fragTrans.commit();
    }

    private void afterProcessing(){

                //show hidden layout and make the waiting hidden through visibility, then add the fragment bellow...
        FragmentTransaction fragTrans = this.getSupportFragmentManager().beginTransaction();
        fragTrans.add(R.main.layout_list_items,
                          new FragmentList());
        fragTrans.replace(R.main.layout_detail,
                          new FragmentB());
        fragTrans.commit();
    }

}

Upvotes: 1

vasart
vasart

Reputation: 6702

Try this code without calling any setContentView

fragmentTransaction.add(android.R.id.content, Fragment.instantiate(MainActivity.this, SplashFragment.class.getName()));

The main approach here is placing fragment in view with id android.R.id.content which is always present before any layout is inflated via setContentView

Upvotes: 1

Related Questions