您好我想知道如何在 viewPager 中打乱片段的顺序?这是我目前所拥有的,请看一看!它虽然不起作用。顺便说一句,我的 shufflebutton 在操作栏中。
OnCreate 方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPager = (ViewPager) findViewById(R.id.pager);
fragments = getFragments();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), fragments);
mPager.setAdapter(mPagerAdapter);
mPager.setOffscreenPageLimit(words.size() - 1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.flashcard, menu);
return true;
}
按下随机播放时:
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.action_shuffle:
seed = System.currentTimeMillis();
Collections.shuffle(listOfWords, new Random(seed));
Collections.shuffle(fragments, new Random(seed));
mPagerAdapter.notifyDataSetChanged();
mPager.setAdapter(mPagerAdapter);
}
return true;
}
适配器类:
私有类 ScreenSlidePagerAdapter 扩展 FragmentStatePagerAdapter { 私有列表片段;
public ScreenSlidePagerAdapter(FragmentManager fragmentManager,
List<Fragment> fragments) {
super(fragmentManager);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.newInstance(listOfWords.get(position).getId()-1);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
getFragments() 方法:
private List<Fragment> getFragments() {
ArrayList<Integer> categoryList = new ArrayList<Integer>();
listOfWords = new ArrayList<VocabWord>();
listOfWords.clear();
if (RedBoxSelection == true) {
categoryList.add(1);
}
if (YellowBoxSelection == true) {
categoryList.add(2);
}
if (GreenBoxSelection == true) {
categoryList.add(3);
}
List<Fragment> flist = new ArrayList<Fragment>();
if (flashcardsAllWordsSelection == true) {
for (int i = 0; i < words.size(); i++) {
flist.add(ScreenSlidePageFragment.newInstance(i));
listOfWords.add(words.get(i));
}
} else if (flashcardsAllWordsSelection ==false) {
for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < categoryList.size(); j++) {
if (words.get(i).getCategory() == categoryList.get(j)) {
flist.add(ScreenSlidePageFragment.newInstance(i));
listOfWords.add(words.get(i));
}
}
}
}
return flist;
}
}