Rus*_*lGk 5 youtube android fragment android-fragments
我的 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>
Run Code Online (Sandbox Code Playgroud)
片段中的代码
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在主要活动中:
getSupportFragmentManager().beginTransaction().replace(R.id.main_container,fragment).addToBackStack(null).commit();
Run Code Online (Sandbox Code Playgroud)
尝试在 Drawer 中打开 Fragment 时出错:
java.lang.NullPointerException:尝试在 com.google.android.youtube.player.YouTubePlayerSupportFragment.onStart(Unknown来源)
这里的问题是您覆盖了超类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;
}
Run Code Online (Sandbox Code Playgroud)
实际的变量名称和类型超出了本答案的范围。这里重要的是YouTubePlayerView在这里被实例化,并且您覆盖了该方法,因此在onStart()方法(也可以在YouTubePlayerSupportFragment中找到)中调用时YouTubePlayerView为 null 。
public void onStart() {
super.onStart();
this.c.a();
}
Run Code Online (Sandbox Code Playgroud)
因此,基本上,您唯一需要的就是实例化您的VideoFragment类,并且,如果您想要实际的视频,而不是黑盒,则需要在创建片段时对其进行初始化(如下所示: )
public VideoFragment()
{
this.initialize("yourAPIKeyHere", this);
}
Run Code Online (Sandbox Code Playgroud)