我是新手,我正试图使用YouTube API片段显示YouTube视频。我已经搜索并试图找到这个问题,但找不到正确的答案。所以,我想用viewpager来展示youtube视频。第一页是youtube,另一页是图片。所以我尝试在片段上实现youtube api。我得到了这个错误。
下面是我的java代码:
public class VideoFragment extends YouTubePlayerSupportFragment {
YouTubePlayerView youTubeView;
String URL_VIDEO = "CaA-k1l0xa4";
String KEY_DEVELOPER = "api key";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.video_gallery, container, false);
YouTubePlayerSupportFragment youTubePlayerSupportFragment = (YouTubePlayerSupportFragment) getFragmentManager().findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerSupportFragment.initialize(KEY_DEVELOPER, new OnInitializedListener() {
@Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1,
boolean arg2) {
// TODO Auto-generated method stub
arg1.cueVideo(URL_VIDEO);
}
@Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
}
这是我的布局
<?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" >
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="@+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
这是我的日志目录:
07-21 03:57:32.042: E/AndroidRuntime(27582): FATAL EXCEPTION: main
07-21 03:57:32.042: E/AndroidRuntime(27582): Process: com.indomultimedia.hellobali, PID: 27582
07-21 03:57:32.042: E/AndroidRuntime(27582): java.lang.NullPointerException
07-21 03:57:32.042: E/AndroidRuntime(27582): at com.google.android.youtube.player.YouTubePlayerSupportFragment.onStart(Unknown Source)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.Fragment.performStart(Fragment.java:1332)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:906)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.view.ViewPager.populate(ViewPager.java:804)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.View.measure(View.java:17357)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.View.measure(View.java:17357)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1751)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.ScrollView.onMeasure(ScrollView.java:468)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.View.measure(View.java:17357)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.View.measure(View.java:17357)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-21 03:57:32.042: E/AndroidRuntime(27582): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:38 2)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.View.measure(View.java:17357)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-21 03:57:32.042: E/AndroidRuntime(27582): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2505)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.View.measure(View.java:17357)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2175)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1316)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1200)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6388)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.Choreographer.doCallbacks(Choreographer.java:603)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.Choreographer.doFrame(Choreographer.java:573)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.os.Handler.handleCallback(Handler.java:733)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.os.Handler.dispatchMessage(Handler.java:95)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.os.Looper.loop(Looper.java:157)
07-21 03:57:32.042: E/AndroidRuntime(27582): at android.app.ActivityThread.main(ActivityThread.java:5293)
07-21 03:57:32.042: E/AndroidRuntime(27582): at java.lang.reflect.Method.invokeNative(Native Method)
07-21 03:57:32.042: E/AndroidRuntime(27582): at java.lang.reflect.Method.invoke(Method.java:515)
07-21 03:57:32.042: E/AndroidRuntime(27582): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-21 03:57:32.042: E/AndroidRuntime(27582): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-21 03:57:32.042: E/AndroidRuntime(27582): at dalvik.system.NativeStart.main(Native Method)
谁能帮我解决这个错误? 在调用initialize之前,首先通过
创建YouTubePlayerSupportFragmentYouTubePlayerSupportFragment youTubeFragment =
new YouTubePlayerSupportFragment().newInstance();
然后通过
提交FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_fragment, youTubeFragment).commit();
我看到一些使用getActivity(). getsupportfragmentmanager()代替getChildFragmentManager()的例子。不知道哪个更正确
我正在做类似的事情,这是我认为你应该做的:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.examples.ViewPagerWithVideo$PlaceholderFragment">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:contentDescription="@string/test"
android:scaleType="centerCrop"
tools:src="@drawable/image_1"
android:visibility="invisible"
/>
<FrameLayout
android:id="@+id/youtube_fragment_view_pager_placeholder"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:visibility="invisible"
/>
</RelativeLayout>
你的Activity应该是这样的:
public class ViewPagerWithVideo extends Activity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_with_video);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_view_pager_with_video, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements YouTubePlayer.OnInitializedListener {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
int[] images = new int[] {R.drawable.image_1, R.drawable.image_2 };
private static final int RECOVERY_DIALOG_REQUEST = 1;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_pager_with_video, container, false);
int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
if (sectionNumber > 0) {
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
imageView.setImageResource(images[sectionNumber % images.length]);
imageView.setVisibility(View.VISIBLE);
} else {
YouTubePlayerFragment youTubePlayerFragment = new YouTubePlayerFragment();
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.youtube_fragment_view_pager_placeholder, youTubePlayerFragment, YouTubePlayerFragment.class.getSimpleName());
transaction.commit();
rootView.findViewById(R.id.youtube_fragment_view_pager_placeholder).setVisibility(View.VISIBLE);
}
return rootView;
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.cueVideo("nCgQDjiotG0");
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DeveloperKey.DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerFragment) getFragmentManager().findFragmentByTag(YouTubePlayerFragment.class.getSimpleName());
}
}
}
把特别注意的事实,我不使用一个静态片段,它是动态创建在PlaceholderFragment的onCreateView。此外,我正在使用一个ViewPager与SectionsPagerAdapter扩展FragmentPagerAdapter。我必须在可绘制文件夹中采样图像,如果你想尝试,我添加了以下要点:https://gist.github.com/moxi/953b985bcd41d9fcde7a
可以轻松创建可绘制的文件夹,您可以放置您的示例图像。