我試過了,但是錯誤的列表綁定到recyclerview。我也嘗試了SparseArray,即使這不起作用。當我開始Mainactivity時,getItem()會被調用兩次。我如何處理返回的職位? 我試圖返回viewpager currentItem,即使這不起作用。FragmentStatePagerAdapter處理getItem()位置
MainActivity
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(android.support.v4.app.FragmentManager fragmentManager, int tabCount)
{
super(fragmentManager);
this.mNumOfTabs = tabCount;
}
@Override
public Fragment getItem(int position) {
return Categories_Fragment.newInstance(position);
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
Categories_Fragment
public class Categories_Fragment extends Fragment
{
private RecyclerView lvMessages;
private int fromPage;
public static Categories_Fragment newInstance(int num) {
Categories_Fragment f = new Categories_Fragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("from", num);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
fromPage = getArguments().getInt("from");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.categories_filter, container, false);
lvMessages = (RecyclerView)rootView.findViewById(R.id.lv_categories_filter);
LinearLayoutManager x = new LinearLayoutManager(getActivity());
x.setOrientation(LinearLayoutManager.VERTICAL);
lvMessages.setLayoutManager(x);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// bind different data to the RecyclerView based on fromPage value.
}
}
嘗試將片段設置爲靜態:'公共靜態類Categories_Fragment擴展Fragment' –
請張貼在那裏引用PagerAdapter代碼。我認爲主要問題是「getItem()被調用兩次...」 –
這應該適合你。實現一個僅在片段可見時才被調用的接口。 http://stackoverflow.com/a/24386516/2102304 – shreyas