【发布时间】:2019-11-03 23:56:27
【问题描述】:
我有一个带有片段的基本应用程序。我的 activity_main.xml 有一个
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="200dp"
android:background="@android:color/holo_green_light" />
在我的一个片段 .xml 文件中,我有一个
<fragment
android:tag="youtube_tag"
android:id="@+id/youtube_player_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginBottom="8dp"/>
我要初始化的。我是从我的 MainActivity.java 做的。我的 onCreate 函数:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...some other code...
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new RadioFragment()).commit();
...some other code...
initializeYoutubePlayer();
....some other code....
}
initializeYoutubePlayer(); 在哪里:
youTubePlayerFragment = (YouTubePlayerSupportFragment)getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
....some other code...
而 RadioFragment 是所需片段的 java 文件,它的内容是:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_radio, container, false);
}
initializeYoutubePlayer(); 中的行返回一个空指针,然后在代码中我得到 NPE。
【问题讨论】:
-
为什么你的 Activity 会进入 Fragment 的布局?添加
YouTubePlayerSupportFragment的片段不应该是与之交互的片段吗? -
尝试使用下面一个
-
@ianhanniballake 所以你建议我将所有与 YTPF 相关的代码移到 Fragments Java 文件中?
-
或者直接将
<fragment>移动到你的Activity布局中。 Fragment 的全部意义在于封装 UI 的一部分。