我有2个片段,A和B.片段B包含recyclerview,并在加载片段B时填充。但是,当我按下片段B然后我回到片段A时,我尝试再次回到片段B但是没有填充recyclerview。
奇怪的是,在我更改屏幕方向后,它确实会填充。
如何在返回片段B后填充recyclerview?
在片段B的onCreateView中设置适配器:
@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 :(得分:0)
初始化适配器并填充数据后,您没有调用 adapter.notifyDataSetChanged();
。