在片段中重新膨胀视图的含义是什么?

时间:2014-10-13 08:33:04

标签: android android-fragments fragment android-inflate

在向片段添加用户界面时,每次调用onCreateView时都会显示给视图充气:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

参考:http://developer.android.com/guide/components/fragments.html#UI

如果我将缓存的视图缓存并在下次调用时返回该内容,例如:

public static class ExampleFragment extends Fragment {
    private View mView = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(mView == null){
            mView = inflater.inflate(R.layout.example_fragment, container, false);
        }else{
            //detach mView from previous parent if exist
            ...
        }
        return mView;
    }
}

1 个答案:

答案 0 :(得分:4)

片段管理器已经为您处理了这样的优化。

只有在需要创建片段视图时才会调用

onCreateView()。当它已经在可用状态下创建时,将不会调用onCreateView()