要使用Androidx和YouTubePlayerSupportFragment,需要进行以下步骤:
build.gradle
文件中,确保已启用Androidx。将以下代码添加到文件的顶部:android {
...
defaultConfig {
...
// 添加以下行
useAndroidX true
// 添加以下行
multiDexEnabled true
}
...
}
dependencies {
...
// 添加以下行
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
// 添加以下行
implementation 'androidx.multidex:multidex:2.0.1'
// 添加以下行
implementation 'com.google.android.youtube:youtube-android-player:10.0.1'
}
YouTubePlayerSupportFragment
实例并将其添加到您的布局文件中。例如,在您的activity_main.xml
文件中添加以下代码:
MainActivity
(或其他活动)中,使用以下代码初始化和配置YouTubePlayerSupportFragment
:import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final String API_KEY = "YOUR_API_KEY";
private static final String VIDEO_ID = "YOUR_VIDEO_ID";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerSupportFragment youTubePlayerFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(API_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.cueVideo(VIDEO_ID);
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, 1).show();
} else {
String errorMessage = String.format("Error initializing YouTube player: %s", errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
}
请确保将API_KEY
替换为您的YouTube API密钥,并将VIDEO_ID
替换为您要播放的YouTube视频的ID。
这样,您就可以在Android应用程序中使用Androidx和YouTubePlayerSupportFragment了。