Android - 创建Youtube片段时出错

时间:2015-12-14 14:41:31

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

我正在使用Youtube API播放器创建可以播放youtube视频的Android片段。在MainActivity课程中,我收到错误

private void displayView(int position) {
    // update the main content by replacing fragments
    Fragment fragment =null;
    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;
    case 1:
        fragment = new VideoFragment();
        break;
    case 2:
        fragment = new ThirdFragment();
        break;
    default:
        break;
    }
  

类型不匹配:无法从VideoFragment转换为Fragment

但是,当我切换到新代码时:

    private void displayView(int position) {
    // update the main content by replacing fragments
    VideoFragment fragment =null;
    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;
    case 1:
        fragment = new VideoFragment();
        break;
    case 2:
        fragment = new ThirdFragment();
        break;
    default:
        break;
    }

发生此错误

  

类型不匹配:无法从ThirdFragment转换为VideoFragment

MainActivity完整代码:

public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {

final Context context = this;

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);

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    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 arrayonCreateOptionsMenu
    // Home
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    // Video
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    // Photos
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -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
    ) {
        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:
        final Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.custom); 
        dialog.setTitle("Event Story");


        // set the custom dialog components - text, image and button
        TextView text = (TextView) dialog.findViewById(R.id.text);
        text.setText("Develop and maintained by W.I.N Sdn. Bhd");


        Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

        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);


    return super.onPrepareOptionsMenu(menu);
}

/**
 * Diplaying fragment view for selected nav drawer list item
 * */

public void onNavigationDrawerItemSelected(int position) {
    // TODO Auto-generated method stub

}
private void displayView(int position) {
    // update the main content by replacing fragments
    VideoFragment fragment =null;
    switch (position) {
    case 0:
        fragment = new HomeFragment();
        break;
    case 1:
        fragment = new VideoFragment();
        break;
    case 2:
        fragment = new ThirdFragment();
        break;
    default:
        break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.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(mTitle);
}

@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);
}
public void openBrowser(View view){

    //Get url from tag
    String url = (String)view.getTag();

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_BROWSABLE);

    //pass the url to intent data
    intent.setData(Uri.parse(url));

    startActivity(intent);
}}

VideoFragment.java

public class VideoFragment extends YouTubeFailureRecoveryActivity {


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.videoview_fragment);

    YouTubePlayerFragment youTubePlayerFragment =
    (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.VideoView);
    youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
  }

  @Override
  public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
      boolean wasRestored) {
    if (!wasRestored) {
      player.cueVideo("https://www.youtube.com/watch?v=pzWfjOaAbcE");
    }
  }

  @Override
  protected YouTubePlayer.Provider getYouTubePlayerProvider() {
    return (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.VideoView);
  }

}

1 个答案:

答案 0 :(得分:0)

碎片和活动不是一回事。活动不会从片段look at this question继承。

如果VideoFragment继承了Fragment,并假设HomeFragment和ThirdFragment也从Fragment继承,那么第一种方法应该可行。