我遇到了同样的问题 - 我想将 YouTube 播放器添加到我的应用程序中,但我不想从中删除 Sherlock(基于支持库)。糟糕的是,我无法使用任何播放器,因为我遇到了错误(片段膨胀、YouTubePlayerView 无法在没有特殊 Activity 的情况下启动等等)。
什么有效:我使用了 SherlockFragmentActivity、FragmentManager (getSupportFragmentManager()) 和 YouTubePlayerSupportFragment。我没有将它添加到 XML 中,而是从代码中创建了所有内容。我的布局如下所示:
<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"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/fragmentz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
和Java代码:
package com.example.youtubetesting;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.OnInitializedListener;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
YouTubePlayerSupportFragment fragment = new YouTubePlayerSupportFragment();
fragmentTransaction.add(R.id.fragmentz, fragment);
fragmentTransaction.commit();
fragment.initialize("Your API KEY HERE",
new OnInitializedListener() {
@Override
public void onInitializationSuccess(Provider arg0,
YouTubePlayer arg1, boolean arg2) {
if (!arg2) {
arg1.loadVideo("wKJ9KzGQq0w");
}
}
@Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
}
});
}
}
当我以正常方式膨胀视图时,我不知道为什么 Android 会返回错误,但这非常有效。