Reputation: 1623
I add two fragments to ViewPager in MainActivity dynamically,while I'm trying to get the sub view of the fragments, Fragment.getView() always return null, how can I solve this problem? Thanks in advance.
mLinearLayout= (LinearLayout)fragments.get(0).getView().findViewById(R.id.linear_layout);
mRelativeLayout= (RelativeLayout) fragments.get(1).getView().findViewById(R.id.relative_layout);
Upvotes: 1
Views: 2656
Reputation: 4086
If I were you, I would use the fragments' onCreateView()
to bind the views, then let the parent Activity
know about the views through an Interface in onActivityCreated()
.
Your interface could look like
public interface ViewInterface {
void onLinearLayoutCreated(LinearLayout layout);
void onRelativeLayoutCreated(RelativeLayout layout);
}
and then in each fragment
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");
}
...
}
and then in your parent Activity
that implements ViewInterface
void onLinearLayoutCreated(LinearLayout layout) {
//do something with LinearLayout
...
}
Upvotes: 5
Reputation: 13865
Define a interface in the Fragment
. Implement it in Activity
. You will have the Activity
instance in the Fragment
. Now, inside onActivityCreated()
of Fragment
, call the interface method with Activity
instance to notify that now the getView()
returns its View
.
Upvotes: 0