【问题标题】:Black screen during setContentView executionsetContentView 执行期间黑屏
【发布时间】:2011-10-21 08:02:28
【问题描述】:

我有一个MainActivity。有时在加载时我会观察一秒钟的黑屏。 我测量了onCreate 方法中的操作时间,发现setContentView(R.layout.main_screen); 花费了超过一秒 我更喜欢在setContentView 执行期间显示上一个屏幕(在我的情况下为启动屏幕)而不是这个黑屏。 如何摆脱这个黑屏?

似乎 android 以某种方式预加载布局,有时会出现此类问题。但是如果我终止我的进程并启动应用程序,我总是会看到这个黑屏。

【问题讨论】:

    标签: android layout android-activity


    【解决方案1】:
    1. 使用静态变量来处理View 缓存。
    2. 使用AsyncTask 不要冻结您的来源Activity
    3. 使用LayoutInflater 扩充View 布局并将其缓存
    4. 在目标Activity的onCreate()中设置缓存

    类似这样的:

    起源活动

    ...
                    //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();
    
    ...
    

    目标活动

    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);
            }
        }
     . . .
    

    您还可以在充气时使用 ProgressDialog 以避免过渡时出现冻结感。

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 2012-12-11
      • 2018-10-15
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多