Android 如何在我的SupportFragment中添加YouTube播放器?
我的XML代码:Android 如何在我的SupportFragment中添加YouTube播放器?,android,android-fragments,youtube,fragment,Android,Android Fragments,Youtube,Fragment,我的XML代码: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" style="@style/Container.MainBackground" android:layout_width="match_parent" android:layout_height="m
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/Container.MainBackground"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:layout_alignParentTop="true"
android:id="@+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
尝试在抽屉中打开碎片时出错:
java.lang.NullPointerException:尝试调用虚拟方法“void”
com.google.android.youtube.player.YouTubePlayerView.a()'在空
对象引用位于
com.google.android.youtube.player.YouTubePlayerSupportFragment.onStart(未知
(来源)
这里的问题是,您要从超级类YouTubePlayerSupportFragment覆盖onCreateView()方法,该方法不是抽象的,实际上有一个实现,如图所示:
public View onCreateView(LayoutInflater var1, ViewGroup var2, Bundle var3) {
this.c = new YouTubePlayerView(this.getActivity(), (AttributeSet)null, 0, this.a);
this.a();
return this.c;
}
实际变量名和类型超出了此答案的范围。
这里重要的是YouTubePlayerView在这里被实例化,您将覆盖该方法,因此YouTubePlayerView在onStart()方法中调用时为空(也可在YouTubePlayerSupportFragment中找到)
因此,基本上,您只需要实例化VideoFragment类,如果您想要实际的视频,而不是黑盒,则需要在创建片段时初始化片段(如下所示:)
有什么解决办法吗?我在Xamarin遇到了这个问题,你的帖子救了我!我只需要在构造函数中使用
Initialize
方法。还有非常好的解释谢谢!
getSupportFragmentManager().beginTransaction().replace(R.id.main_container,fragment).addToBackStack(null).commit();
public View onCreateView(LayoutInflater var1, ViewGroup var2, Bundle var3) {
this.c = new YouTubePlayerView(this.getActivity(), (AttributeSet)null, 0, this.a);
this.a();
return this.c;
}
public void onStart() {
super.onStart();
this.c.a();
}
public VideoFragment()
{
this.initialize("yourAPIKeyHere", this);
}