2017-04-13 112 views
0

我有2個片段,A和B.片段B包含recyclerview,並且在加載片段B時填充它。但是,當我按回B片段並回到片段A時,我嘗試再次返回片段B,但回收站視圖未填充。Recyclerview僅在方向更改後填充

奇怪的是,它改變屏幕方向後會填充。

如何在回到片段B後填充回收站視圖?

在onCreateView設置B片段適配器:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) 
{ 
    recyclerView = (RecyclerView) view.findViewById(R.id.rvPlaylists); 
    recyclerView.setHasFixedSize(true); 
    layoutManager = new GridLayoutManager(getActivity(),1); 
    recyclerView.setLayoutManager(layoutManager); 
    PlaylistAdapter adapter = new PlaylistAdapter(savedPlaylists); 
    recyclerView.setAdapter(adapter); 
} 

適配器:

public class PlaylistAdapter extends 
RecyclerView.Adapter<PlaylistAdapter.ViewHolder> 
{ 
    private Context mContext; 
    private ArrayList<Playlist> mPlaylists; 
    private LayoutInflater mInflater; 

    public PlaylistAdapter(ArrayList<Playlist> playlists) 
    { 
     mPlaylists = playlists; 
    } 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
    { 
     View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.playlist_recyclerview_item, parent, false); 
     return new ViewHolder(v); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) 
    { 
     Playlist currentPlaylist = mPlaylists.get(position); 
     holder.tvName.setText(currentPlaylist.getName()); 
     holder.btnPlayPlaylist.setOnClickListener(new View.OnClickListener(){ 
      @Override 
      public void onClick(View v) { 
       Log.d("btn clicked","mlk"); 
      } 
     }); 
    } 

    @Override 
    public int getItemCount() 
    { 
     return mPlaylists.size(); 
    } 


    public class ViewHolder extends RecyclerView.ViewHolder 
    { 
     public TextView tvName; 
     public ImageButton btnPlayPlaylist; 

     public ViewHolder(View v) 
     { 
      super(v); 
      tvName = (TextView) v.findViewById(R.id.lblPlaylistName); 
      btnPlayPlaylist = (ImageButton) v.findViewById(R.id.btnPlayPlaylist); 
     } 

    } 

加載片段B:

public void navigateFromPlaylistFragmentToSavedPlaylistFragment() 
{ 
    getFragmentManager().beginTransaction().replace(R.id.activity_main, new SavedPlaylistFragment()).addToBackStack("navigatefromplaylistfragmenttosavedplaylistfragment") 
      .commit(); 
} 
+0

FragmentTransaction transaction = getFragmentManager()。beginTransaction(); transaction.detach(this).attach(this).commit(); 試試.... –

+0

我不知道我應該把它放在哪裏。我用replace方法在我的主要活動中加載了片段,加載情況良好,但問題是我的recyclerview未填充。 – Ferre12

+0

http://stackoverflow.com/questions/23212162/how-to-move-from-one-fragment-to-another-fragment-on-click-of-a-imageview-in-and –

回答

0

你沒有打電話給adapter.notifyDataSetChanged();初始化適配器後,並填充數據。

+0

這沒有奏效。當recyclerview中的數據沒有改變時,我也有問題。 – Ferre12