我是一名有用的助手,可以为您翻译文本。
我有一个View类,想将其添加到我的Fragment中,但我无法弄清如何实现。
以下是我的Fragment:
我尝试在Fragment的onViewCreated方法中将SingleTouchEventView添加到片段中,但不起作用。
以下是错误:
请帮忙,我如何将我的视图正确地添加到片段布局中?
我有一个View类,想将其添加到我的Fragment中,但我无法弄清如何实现。
以下是我的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));
}
我尝试在Fragment的onViewCreated方法中将SingleTouchEventView添加到片段中,但不起作用。
以下是错误:
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
请帮忙,我如何将我的视图正确地添加到片段布局中?