简体   繁体   中英

Fragment loading animation don't start until startactivity intent completed in Android

There are two activities which are main and reding. When I click the open book in main activity, a loading fragment should be appear on screen until reading activity loaded completely.

In activity main, activity reading open click event:

@Override
public void onClick(View v) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
        // fragment fade in enough
        .setCustomAnimations(R.anim.fade_in, 0, 0, 0)
        // main_root in activity main.
        .add(R.id.main_root, new BookLoadingFragment(), "BookLoaderFragment")
        .addToBackStack("BookLoaderFragmentStackTag")
        .commit();
    fragmentManager.executePendingTransactions();

    Intent intent = new Intent(context, ReadBookActivity.class);
    context.startActivity(intent);
}

So by the above code, loading fragment don't appear until reading activity opened completely (It appear without setCustomAnimations()). I've tried creating new thread or async task for fragment but there was an error creating fragmet not allowed outside of ui thread. Also I've to create fragment in main activity because reading activity has many other fragments attached it with onActivityCreated().

public final class BookLoadingFragment extends Fragment {

   ...

   public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
      super.onViewCreated(view, savedInstanceState);
    
      Intent intent = new Intent(this.getContext(), ReadBookActivity.class);
      startActivity(intent);
   }
}

Start ReadBookActivity after BookLoadingFragment was created

Your BookLoadingFragment freezing because main ui thread is no longer at its activity, you cannot work on it anymore. You should add loading fragment in what activity you load and show loading fragment until loaded second activity with AsyncTask.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_book);
    
    AddLoadingFragment();
    new AsyncLoading().execute();
}

class AsyncLoading extends AsyncTask<String,Integer,String> {
    
    public AsyncAppOpen() {
        super();
    }
    @Override
    protected String doInBackground(String... strings) {
        // Preapare background process only! Get data from Database or build Rcyvlerview adapter.
        return null;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // doInBackground finished and it's time to preapare ui thread process. Build RecyclerView or some ui tools.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM