我在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);
答案 0 :(得分:5)
如果我是你,我会使用碎片' onCreateView()
绑定视图,然后让父Activity
通过onActivityCreated()
中的接口了解视图。
您的界面可能看起来像
public interface ViewInterface {
void onLinearLayoutCreated(LinearLayout layout);
void onRelativeLayoutCreated(RelativeLayout layout);
}
然后在每个片段中
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");
}
...
}
然后在实现Activity
ViewInterface
中
void onLinearLayoutCreated(LinearLayout layout) {
//do something with LinearLayout
...
}
答案 1 :(得分:0)
在Fragment
中定义界面。在onActivityCreated()
中实施。您将在Fragment
中拥有Activity
个实例。现在,在getView()
的{{1}}内,使用View
实例调用接口方法,以通知 FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,interested_in,gender,birthday,email,age_range,name,picture.width(480).height(480)"]).startWithCompletionHandler({ (connection, result, error) -> Void in
print(result)
})
现在返回其/users/search
。