问题
onCreate中inflate的view太多导致activity跳转较慢
思路
异步加载view
代码
定义
private LinearLayout container = null;
private MyAsycnTask myAsycnTask;
使用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
container = findViewById(R.id.container);
myAsycnTask = new MyAsycnTask(this);
myAsycnTask.execute();
}
异步代码
private static class MyAsycnTask extends AsyncTask<Void, View, View>{
private WeakReference<ContentActivity> contentActivityWeakReference;
public MyAsycnTask(ContentActivity contentActivity){
this.contentActivityWeakReference = new WeakReference<ContentActivity>(contentActivity);
}
@Override
protected View doInBackground(Void... voids) {
ContentActivity contentActivity = contentActivityWeakReference.get();
if (contentActivity != null){
for (int i = 0; i < 10; i++){
View view = LayoutInflater.from(contentActivity).inflate(R.layout.content_item, contentActivity.container, false);
publishProgress(view);
}
}
return null;
}
@Override
protected void onProgressUpdate(View... values) {
super.onProgressUpdate(values);
ContentActivity contentActivity = contentActivityWeakReference.get();
if (contentActivity != null){
contentActivity.container.addView(values[0]);
}
}
}