YouTubePlayerFragment无法转换为android.support.v4.app.Fragment

前端之家收集整理的这篇文章主要介绍了YouTubePlayerFragment无法转换为android.support.v4.app.Fragment前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经坚持了3天了,经过大量搜索后尝试了我遇到的一切,这篇文章真的是最后的手段,我试图用导航抽屉打开一个YouTubePlayerFragment

YouTubePlayerFragment无法转换为android.support.v4.app.Fragment是问题所在

编辑问题:我已经更新了代码,因为我使用了YouTubePlayerSupportFragment而不是YouTubePlayerFragment,我在主要活动中的displayView方法中遇到错误(案例4:fragment = new Youtube(); break;)说无法从Youtube转换为片段,我无法得到一个logcat,因为我甚至无法运行它

编辑问题2:代码再次更新,但现在我有运行时问题,继承logcat

07-22 22:15:09.782: E/AndroidRuntime(20603): FATAL EXCEPTION: main
07-22 22:15:09.782: E/AndroidRuntime(20603): Process: net.frankandwalters,PID: 20603
07-22 22:15:09.782: E/AndroidRuntime(20603): java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.youtube.player.YouTubePlayerView.a()' on a null object reference
07-22 22:15:09.782: E/AndroidRuntime(20603):    at com.google.android.youtube.player.YouTubePlayerSupportFragment.onStart(Unknown Source)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.support.v4.app.Fragment.performStart(Fragment.java:1502)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:957)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.os.Handler.handleCallback(Handler.java:739)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.os.Handler.dispatchMessage(Handler.java:95)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.os.Looper.loop(Looper.java:135)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at android.app.ActivityThread.main(ActivityThread.java:5351)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at java.lang.reflect.Method.invoke(Native Method)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at java.lang.reflect.Method.invoke(Method.java:372)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
07-22 22:15:09.782: E/AndroidRuntime(20603):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

继承了java代码,希望有人能帮忙,谢谢

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;

public class Youtube extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener {

    public static Youtube newInstance() {
        Youtube fragment = new Youtube();
        return fragment;
    }

    private void init(){
        initialize("AIzaSyBybXMSBPvhMKgM4RKqpneb4Tf4yObVAkY",this);
    }

    public Youtube() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.youtubefragment,container,false);

        Youtube ytf = newInstance();
        ytf.init();
        getActivity().getSupportFragmentManager().beginTransaction()
                .add(R.id.youtube_player,ytf)
                .commit();


        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,YouTubePlayer player,boolean wasRestored) {
        if (!wasRestored) {
            player.cueVideo("nCgQDjiotG0");
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider,YouTubeInitializationResult youTubeInitializationResult) {
        Toast.makeText(getActivity(),"Failured to Initialize!",Toast.LENGTH_LONG).show();
    }


}

这是xml代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="@drawable/background"
    android:id="@+id/fragment_youtube_player_holder" >



<fragment
  android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
  android:id="@+id/youtube_player"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>




</LinearLayout>

这是包含导航抽屉的主要活动

import java.util.ArrayList;

import net.frankandwalters.adapter.NavDrawerListAdapter;
import net.frankandwalters.model.NavDrawerItem;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class MainActivity extends FragmentActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;


    // nav drawer title
    //private CharSequence mDrawerTitle;

    // used to store app title
    //private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        //mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0],navMenuIcons.getResourceId(0,-1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],navMenuIcons.getResourceId(1,-1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2],navMenuIcons.getResourceId(2,-1)));
        // Communities,Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3],navMenuIcons.getResourceId(3,-1)));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4],navMenuIcons.getResourceId(4,-1)));
        // What's hot,We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5],navMenuIcons.getResourceId(5,-1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6],navMenuIcons.getResourceId(6,-1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[7],navMenuIcons.getResourceId(7,-1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[8],navMenuIcons.getResourceId(8,-1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[9],navMenuIcons.getResourceId(9,-1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[10] + " Disc 3",navMenuIcons.getResourceId(10,-1)));


        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.drawable.ic_drawer,//nav menu toggle icon
                R.string.app_name,// nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                //getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                //getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened,hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(drawerOpen && !drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
//      case 0:
//          fragment = new Home();
//          break;
//      case 1:
//          fragment = new Forum();
//          break;
//      case 2:
//          fragment = new Facebook();
//          break;
//      case 3:
//          fragment = new Twitter();
//          break;
        case 4:

            //fragment  = Youtube.newInstance();

//          if(YouTubeIntents.isYouTubeInstalled(getBaseContext()) ) {
//                 if(YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(getBaseContext()) != YouTubeInitializationResult.SUCCESS) {
//                    // fragment = new Youtube();
//                     Intent intent = YouTubeIntents.createUserIntent(this,"FrankandWalters");
//                      startActivity(intent);
//                     
//               } else  {
                       fragment = new Youtube();
                     //Intent intent = YouTubeIntents.createUserIntent(this,"FrankandWalters");
                       // startActivity(intent);
//               }
//              }
            break;
//      case 5:
//          fragment = new Instagram();
//          break;
//      case 6:
//          fragment = new Google();
//          break;
//      case 7:
//          fragment = new Gigography();
//          break;
//      case 8:
//          fragment = new Discography();
//          break;
//      case 9:
//          fragment = new Lyrics();
//          break;
//      case 10:
//          fragment = new Souvenirs();
//          break;

        default:
            break;
        }

        if (fragment != null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.frame_container,fragment).commit();

            // update selected item and title,then close the drawer
            mDrawerList.setItemChecked(position,true);
            mDrawerList.setSelection(position);
            //setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity","Error in creating fragment");
        }
    }

//  @Override
//  public void setTitle(CharSequence title) {
//      mTitle = title;
//      getActionBar().setTitle("The Frank And Walters");
//  }

    /**
     * When using the ActionBarDrawerToggle,you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }


}

解决方法@H_502_24@
将YouTubePlayerFragment替换为 YouTubePlayerSupportFragment,因为这是使用Fragment支持版本的版本.

原文链接:https://www.f2er.com/android/308942.html

猜你在找的Android相关文章