Reputation: 1831
I am trying to load a different video into a YoutubePlayer fragment when a button is clicked. My button has an onclick listener of testClick. When I click the button, I get the following exception: "UsupportedExeception: no views can be added on top of player". The initialize method also isn't being called when I initialize the new video from my onclick method. How can I a new YouTubeVideo to be loaded into the previously used YouTubePlayerFragment, and how I can get the initialize method to be called from my onClick method?
public class ExersizeListActivity extends Activity implements
YouTubePlayer.OnInitializedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exersize_list);
}
public void testClick(View v) {
//new YouTube Fragment to replace old one
YouTubePlayerFragment youTubePlayerFragment=YouTubePlayerFragment.newInstance();
youTubePlayerFragment.initialize(YoutubeAPIKey.API_KEY, this);
FragmentManager fragManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragManager.beginTransaction();
fragmentTransaction.replace(R.id.youtube_fragment, youTubePlayerFragment);
fragmentTransaction.commit();
}
@Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
Log.e(null, "it bombed");
}
//not being called, and in current state would reinitialize with the same video
@Override
public void onInitializationSuccess(Provider arg0,
YouTubePlayer youtubePlayer, boolean arg2) {
youtubePlayer.cueVideo("YNKehLXpLRI");
}
}
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<fragment
android:id="@+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/randomizeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Randomize!"
android:layout_below="@+id/youtube_fragment"
android:onClick="testClick"/>
</RelativeLayout>
Upvotes: 2
Views: 1610
Reputation: 2792
Rather than defining the fragment in the xml layout file with the <fragment>
tag, define a FrameLayout container, necessary when changing fragments dinamically at runtime:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<FrameLayout
android:id="@+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/randomizeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Randomize!"
android:layout_below="@+id/youtube_fragment"
android:onClick="testClick"/>
</RelativeLayout>
You will need to add the first YouTubeVideoFragment
in onCreate()
with a FragmentTransaction
, and when the user clicks the button, the code you already have in testClick()
should work.
Upvotes: 3