i have a View Class which i want to add to my Fragment, but i cant figure out how to do it.
Here is my fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_pong, container, true);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RelativeLayout pongField = (RelativeLayout) getActivity().findViewById(R.id.pongGameField);
pongField.addView(new SingleTouchEventView(getActivity(), null));
}
I try to add the SingleTouchEventView to the fragment in the onViewCreated method of the fragment, but it doesnt work.
Here is the error:
12-18 14:49:11.479 18177-18177/com.example.pymdev.pym E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3439)
at android.view.ViewGroup.addView(ViewGroup.java:3310)
at android.view.ViewGroup.addView(ViewGroup.java:3255)
at android.view.ViewGroup.addView(ViewGroup.java:3231)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
12-18 14:49:34.129 18177-18177/com.example.pymdev.pym I/Process: Sending signal. PID: 18177 SIG: 9
Please help, how can i add my View to the fragment layout properly?
A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation.
(In this case, this is false because the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout.)
For more detail refer to the documentation
Use this
View view=inflater.inflate(R.layout.fragment_pong, container,false);
instead of
View view=inflater.inflate(R.layout.fragment_pong, container,true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With