Fragment.getView()始终返回null

Jia*_*ang 1 android android-fragments

我在MainActivity中动态地向ViewPager中添加了两个片段,而我试图获取片段的子视图,Fragment.getView()总是返回null,如何解决这个问题?提前致谢。

mLinearLayout= (LinearLayout)fragments.get(0).getView().findViewById(R.id.linear_layout);
    mRelativeLayout= (RelativeLayout) fragments.get(1).getView().findViewById(R.id.relative_layout);
Run Code Online (Sandbox Code Playgroud)

roa*_*ter 5

如果您是我,则可以使用片段onCreateView()来绑定视图,然后Activity通过中的接口让父母知道这些视图onActivityCreated()

您的界面可能看起来像

public interface ViewInterface {
  void onLinearLayoutCreated(LinearLayout layout);
  void onRelativeLayoutCreated(RelativeLayout layout);
}
Run Code Online (Sandbox Code Playgroud)

然后在每个片段中

public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.fragment_layout, inflater, false);
  mLinearLayout = layout.findViewById(R.id.linear_layout);
  ...
  return layout;
}

...

public void onActivityCreated (Bundle savedInstanceState) {
  super.onActivityCreated(savedInstanceState);
  try {
    ViewInterface callback = (ViewInterface) getActivity();
    callback.onLinearLayoutCreated(mLinearLayout);
  } catch (ClassCastException e) {
    Log.e("ERROR", getActivity().getName()+" must implement ViewInterface");
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

然后在您的父母Activity中实施ViewInterface

void onLinearLayoutCreated(LinearLayout layout) {
  //do something with LinearLayout
  ...
}
Run Code Online (Sandbox Code Playgroud)