我的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="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>
片段中的代码
public class VideoFragment extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "MyKey";
static private final String VIDEO = "ToMpzhdUD1Q";
static private final String VIDEO1 = "K77avo920Jc";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View videoView = inflater.inflate(R.layout.video_fragment, container, false);
getActivity().setTitle("Youtube");
YouTubePlayerSupportFragment youTubePlayerSupportFragment = new YouTubePlayerSupportFragment();
youTubePlayerSupportFragment.initialize(DEVELOPER_KEY, this);
return videoView;
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
List<String> list = new ArrayList<>();
list.add(VIDEO);
list.add(VIDEO1);
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.cueVideos(list);
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getContext(), "FAIL!" + youTubeInitializationResult.toString(), Toast.LENGTH_LONG)
.show();
}
}
在主要活动中:
getSupportFragmentManager().beginTransaction().replace(R.id.main_container,fragment).addToBackStack(null).commit();
我尝试在抽屉中打开片段时出错:
java.lang.NullPointerException:尝试调用虚方法'void com.google.android.youtube.player.YouTubePlayerView.a()'在null上 对象参考 com.google.android.youtube.player.YouTubePlayerSupportFragment.onStart(未知 源)
答案 0 :(得分:1)
这里的问题是你从超类 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 在此处进行实例化,并且您覆盖了该方法,因此当 onStart()中调用时, YouTubePlayerView 为空方法(也可在 YouTubePlayerSupportFragment 中找到)。
public void onStart() {
super.onStart();
this.c.a();
}
因此,基本上,您唯一需要的是实例化 VideoFragment 类,如果您想要实际视频而不是黑盒子,则需要初始化片段,创作的时间,(像这样:):
public VideoFragment()
{
this.initialize("yourAPIKeyHere", this);
}