2017-01-18 7 views
1

У меня есть класс VideoFragment в моей деятельности.Android, как динамически добавить видеофрагмент в мой макет

public static class VideoFragment extends YouTubePlayerFragment 
     implements YouTubePlayer.OnInitializedListener { 

    private YouTubePlayer player; 
    private String videoId; 
    public int height; 

    public static VideoFragment newInstance() { 
     return new VideoFragment(); 
    } 

    @Override 
    public void onViewCreated(View view, Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 

    } 

    ; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     initialize(getString(R.string.api_key), this); 
    } 

    @Override 
    public void onDestroy() { 
     if (player != null) { 
      player.release(); 
     } 
     super.onDestroy(); 
    } 

    public void setVideoId(String videoId) { 
     if (videoId != null && !videoId.equals(this.videoId)) { 
      this.videoId = videoId; 
      if (player != null) { 
       player.cueVideo(videoId); 
      } 
     } 
    } 

    public void pause() { 
     if (player != null) { 
      player.pause(); 
     } 
    } 

    @Override 
    public void onInitializationSuccess(YouTubePlayer.Provider provider, 
             YouTubePlayer player, boolean restored) { 
     this.player = player; 
     player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT); 
     player.setOnFullscreenListener((VideoOptionTemplate) getActivity()); 
     if (!restored && videoId != null) { 
      player.loadVideo(videoId); 
      // player.play(); 
     } 
     player.play(); 
    } 

    @Override 
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { 
     this.player = null; 
    } 
} 

мне нужно создать цикл со статическим подсчетом, чтобы добавить фрагменты в каждом цикле на мой linearlyout, каждый фрагмент должен иметь другой идентификатор, так что я могу загрузить на Видеосервис YouTube после этого в каждом.

это, как я создать цикл

for(int i=0;i<10;i++) 
{ 
     LayoutInflater inflater = VideoOptionTemplate.this.getLayoutInflater(); 
    View to_add = inflater.inflate(R.layout.video_layout, 
      pagelayout, false); 
    final LinearLayout childlayout = (LinearLayout) to_add.findViewById(R.id.layoutoption);//this layout contains the fragment of     video player with specific id 
    TextView counttxt = (TextView) to_add.findViewById(R.id.counttxt); 
    counttxt.setText(String.valueOf(i + 1)); 
    pagelayout.addView(childlayout, i); 
} 

это мой макет, который я называю в каждом цикле и я добавить в мой родительский макет

<LinearLayout 
    android:id="@+id/uploadlayout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:onClick="upload" 
    android:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"> 

     <ImageView 

      android:id="@+id/optionimg" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:gravity="center" 
      android:paddingBottom="10dp" 
      android:paddingLeft="5dp" 
      android:paddingRight="5dp" 
      android:paddingTop="10dp" 
      android:src="@drawable/video" 

      android:textColor="@android:color/black" /> 


     <EditText 

      android:id="@+id/optionvideo" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="left" 
      android:layout_toRightOf="@+id/subject" 
      android:layout_weight="1" 

      android:background="@android:color/transparent" 
      android:paddingBottom="15dp" 
      android:paddingLeft="5dp" 
      android:paddingRight="10dp" 
      android:paddingTop="15dp" 
      android:text="Add your video" 
      android:textSize="12sp" /> 

    </LinearLayout> 

    <fragment 
     android:id="@+id/video_fragment_container" 
     class="u2vote.activities.VideoOptionTemplate$VideoFragment" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 

     android:layout_gravity="center_horizontal" 
     android:gravity="center" /> 
</LinearLayout> 

ответ

0

Это немного сложнее. Вы, по сути, пытаетесь добавить фрагменты к динамическим представлениям, что очень хорошо не поддерживается из коробки. Тем не менее, есть две вещи, которые вы могли бы, вероятно, сделать:

  1. Вместо добавления фрагмента внутри макета, вы можете заменяющие фрагмент тег с FrameLayout и добавить фрагмент с помощью FragmentTransaction. Для этого вам нужно указать ID FrameLayout, хотя, очевидно, будет одинаковым для всех ваших динамических просмотров . Что вы можете сделать, чтобы обойти эту проблему, чтобы вручную дать те FrameLayout пользовательские идентификаторы, как описано здесь: https://stackoverflow.com/a/18296943/504855

  2. Менее Hacky способ может быть, чтобы обернуть эти фрагменты в другом фрагменте. Библиотека поддержки фрагментов поддерживает дочерние фрагменты, поэтому вы можете повернуть этот макет в фрагмент и добавить в него фрагмент PlayerFragment с помощью getChildFragmentManager() в фрагменте обертки. Затем обертки можно добавить прямо к «pagelayout», используя обычный FragmentManager вашей активности.

 Смежные вопросы

  • Нет связанных вопросов^_^