@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
MyView myView = new MyView(getActivity());
myView.addViews(getViews());
return myView;
}
我知道public void onActivityCreated (Bundle savedInstanceState){}
被調用後onCreateView();
我需要上下文onCreateView()
膨脹自定義佈局。我如何在onActivityCreated()
之前一直獲得有效的上下文(使用getActivity()
)?
可能的解決方案:
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, container, false); //Contains empty RelativeLayout
return view;
}
//Now that we have activity, create custom views and add it to the empty container
public void onActivityCreated (Bundle savedInstanceState){
RelativeLayout layout = (RelativeLayout)view.findViewById(R.id.layout);
MyView myView = new MyView(getActivity());
layout.add(myView);
}
但這種方法增加了額外的視圖層次。
U可以創建構造函數,需要從上下文的活動 –
我不會建議。順便說一下,所有碎片都需要有空的構造函數。如果你想將對象傳遞給Fragment,你可以使用靜態工廠方法。 –
它不一定會添加額外的視圖層次結構。如果碎片中膨脹的佈局只包含您的自定義視圖,那麼不會有額外的開銷。我會編輯我的答案來澄清。 –