Black screen during setContentView execution

2020-07-25 10:23发布

I have a MainActivity. Sometimes when it is loading I observe black screen for a second. I measured timings for operations in onCreate method and discovered that more than one second was spent for setContentView(R.layout.main_screen); I prefer to show previous screen (in my case Splash screen) instead of this black screen during setContentView execution. How can I rid off this black screen?

Seems android in some way preloads layouts and such problems occurs sometimes. But if I kill my process and start app I always see this black screen.

1条回答
【Aperson】
2楼-- · 2020-07-25 10:35
  1. Use a static variable to handle the View cache.
  2. Use an AsyncTask to don't freeze your origin Activity
  3. Use LayoutInflater to inflate the View layout and cache it
  4. In the onCreate() of the target Activity set the cache

Something like this:

Origin activity

...
                //noinspection unchecked
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        LayoutInflater inflater = (LayoutInflater)
                                MainParentActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                        // VERY VERY SLOW action if your Activity is heavy
                        DialerActivity.cachedView = inflater.inflate(R.layout.dialer_portrait, null, false);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        Intent intent = new Intent(MainParentActivity.this, DialerActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        startActivity(intent);
                    }
                }.execute();

...

Target activity

public class DialerActivity extends MainParentActivity {
    static View cachedView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (cachedView != null) {
            setContentView(cachedView);
        } else {
            setContentView(R.layout.dialer_portrait);
        }
    }
 . . .

You can use also a ProgressDialog while inflating to avoid freeze sensation on the transition.

查看更多
登录 后发表回答