Я получаю приведенную ниже ошибку при попытке отобразить проигрыватель Youtube во второй раз.
Caused by: java.lang.IllegalArgumentException: Binary XML file line #44: Duplicate id 0x7f070086, tag null, or parent id 0x7f070022 with another fragment for com.google.android.youtube.player.YouTubePlayerSupportFragment
MainActivity.java is
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.example.sample.VideoPlayerDialog;
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.sample.MESSAGE";
private VideoPlayerDialog mVideoPlayerDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showYoutube(View view) {
mVideoPlayerDialog = new VideoPlayerDialog(MainActivity.this);
showVideoPlayer("");
}
private void showVideoPlayer(String videoUrl) {
runOnUiThread(() -> {
if (!videoUrl.isEmpty()) {
mVideoPlayerDialog.playVideo(videoUrl);
}
if (!mVideoPlayerDialog.isShowing()) {
mVideoPlayerDialog.show();
}
});
}}
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="@string/edit_message"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="@+id/button"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:onClick="showYoutube"
android:text="@string/button_send"
app:layout_constraintBaseline_toBaselineOf="@+id/editText2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/editText2" /></android.support.constraint.ConstraintLayout>
dialog_video_player.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/video_control_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center"
android:orientation="horizontal">
<EditText
android:id="@+id/video_url_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="@string/hint_video_player_url"
android:maxLength="85"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="@+id/play_video_btn"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/play_video" />
<!--android:background="@color/bg_header_upcoming_session_list"-->
<Button
android:id="@+id/close_video_btn"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/close_video" />
</LinearLayout>
<fragment
android:id="@+id/youtube_fragment_id"
class="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/video_control_layout"
android:layout_centerHorizontal="true" />
</RelativeLayout>
VideoPlayerDialog.java
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.youtube.player.YouTubeApiServiceUtil;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
public class VideoPlayerDialog extends Dialog implements YouTubePlayer.OnInitializedListener {
private static final String LOG_TAG = VideoPlayerDialog.class.getSimpleName();
private static final String DEVELOPER_KEY = "XXXXXXXXXXXXXXX";
private static final String YOUTUBE_URL_PREFIX = "https://www.youtube.com/watch?v=";
private String mYoutubeVideoId = null;
private YouTubePlayer mYouTubePlayer;
private EditText mYouTubeUrlText;
private Context mContext;
public VideoPlayerDialog(@NonNull AppCompatActivity context) {
super(context);
mContext = context;
Log.d(LOG_TAG, "VideoPlayerDialog: ");
initialize(context);
}
private void initialize(AppCompatActivity context) {
Log.d(LOG_TAG, "on initialize: ");
if (!checkYouTubeApi()) {
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
Log.d(LOG_TAG, "on checkYouTubeApi: ");
setContentView(R.layout.dialog_video_player);
Log.d(LOG_TAG, "on setContentView: ");
setCancelable(false);
YouTubePlayerSupportFragment mYouTubePlayerFragment = (YouTubePlayerSupportFragment) context.getSupportFragmentManager().findFragmentById(R.id.youtube_fragment_id);
mYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
mYouTubeUrlText = (EditText) findViewById(R.id.video_url_input);
findViewById(R.id.play_video_btn).setOnClickListener(v -> {
if (!mYouTubeUrlText.getText().toString().isEmpty()) {
playVideo();
} else {
Log.d(LOG_TAG, "Error in Play: ");
}
});
findViewById(R.id.close_video_btn).setOnClickListener(v -> {
Log.d(LOG_TAG, "onDestroy: ");
dismiss();
});
}
private boolean checkYouTubeApi() {
boolean ret = true;
YouTubeInitializationResult errorReason = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(mContext);
if (errorReason != YouTubeInitializationResult.SUCCESS) {
String errorMessage;
ret = false;
}
return ret;
}
public void playVideo(String url) {
if (!checkYouTubeApi()) {
return;
}
mYoutubeVideoId = getYoutubeVideoID(url);
if (mYouTubePlayer != null && !mYoutubeVideoId.isEmpty()) {
mYouTubePlayer.loadVideo(mYoutubeVideoId);
}
}
private void playVideo() {
String url = mYouTubeUrlText.getText().toString();
mYoutubeVideoId = getYoutubeVideoID(url);
if (mYoutubeVideoId.isEmpty()) { //video id.
mYoutubeVideoId = url;
url = YOUTUBE_URL_PREFIX + url;
}
Log.d(LOG_TAG, "on playVideo: ");
if (mYouTubePlayer != null && !mYoutubeVideoId.isEmpty()) {
Log.d(LOG_TAG, "on mYoutubeVideoId Play: ");
mYouTubePlayer.loadVideo(mYoutubeVideoId);
}
String urlToSend = YOUTUBE_URL_PREFIX + mYoutubeVideoId;
}
//Parse the youtube url and get the youtube id
public static String getYoutubeVideoID(String youtubeUrl) {
if (TextUtils.isEmpty(youtubeUrl)) {
return "";
}
String video_id = "";
String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String groupIndex1 = matcher.group(7);
if (groupIndex1 != null && groupIndex1.length() == 11)
video_id = groupIndex1;
}
if (TextUtils.isEmpty(video_id)) {
if (youtubeUrl.contains("youtu.be/") ) {
String spl = youtubeUrl.split("youtu.be/")[1];
if (spl.contains("\\?")) {
video_id = spl.split("\\?")[0];
}else {
video_id =spl;
}
}
}
return video_id;
}
@Override
public void show() {
if (!checkYouTubeApi()) {
return;
}
super.show();
}
@Override
public void dismiss() {
if (!checkYouTubeApi()) {
return;
}
if (mYouTubePlayer != null && mYouTubePlayer.isPlaying()) {
mYouTubePlayer.pause();
}
mYouTubePlayer.release();
mYoutubeVideoId = "";
mYouTubeUrlText.getText().clear();
super.dismiss();
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
mYouTubePlayer = youTubePlayer;
Log.d(LOG_TAG, "on mYouTubePlayer: ");
mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
if (!wasRestored) {
mYouTubePlayer.loadVideo(mYoutubeVideoId);
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
public interface VideoPlayerListener {
void onUpdateVideoPlayer(String url, String status);
}
}
Может кто-нибудь сказать, что не так в приведенном выше коде.Извините за задержку с ответом, я не получил разрешения на публикацию всего кода, поэтому создал пример приложения только с частью YouTube.