我用,
@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()
扩展自定义布局。我怎样才能得到一个有效的上下文(使用getActivity()
)之前onActivityCreated()
?
可能的解决方案:
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);
}
但是这种方法增加了一个额外的视图层次。