无法将youtube播放器片段添加到布局中

时间:2016-05-11 05:35:29

标签: android-fragments youtube-api youtube-data-api android-youtube-api

我正在尝试将youtubeplayersupportfragment添加到我的片段内的布局中。 它将片段添加到布局中说 “无法将youtubeplayersupportfragment转换为片段。 这是我的代码

public class combofrag extends Fragment implements View.OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_combofrag, container, false);
    YouTubePlayerSupportFragment youTubePlayerFragment = new YouTubePlayerSupportFragment();

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.youtube_view1, youTubePlayerFragment).commit();

    youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {

        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
            if (!wasRestored) {
                player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
                player.loadVideo("mI8HWnkWk7c");
                player.play();
            }
        }

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
            // YouTube error
            String errorMessage = error.toString();
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
            Log.d("errorMessage:", errorMessage);
        }
    });
    return view;
}

此行有错误

transaction.add(R.id.youtube_view1, youTubePlayerFragment).commit();

1 个答案:

答案 0 :(得分:2)

child fragment manager类型为android.app.FragmentManagerYouTubePlayerSupportFragment类型为android.support.v4(or v7 etc).app.Fragment。你无法将fragment投射到support fragment

将您的combofrag更改为support fragment或将YouTubePlayerSupportFragment更改为fragment以解决此冲突。

我更愿意使用support fragment,而不是仅使用fragment

希望这会有所帮助。