我正在创建一个应用程序,我必须在其中显示与每个类别相关的问题类别和问题。每个问题类别都有不同的问题数量。在选择类别时,我必须将问题屏幕显示为滑动屏幕,这意味着用户可以在滑动时移动到下一个问题。所以,我用两个Fragmelt
设计了一个屏幕。第一个片段是ListFragment
以显示类别列表,另一个片段是ViewPager
以显示滑动问题。我能够在ViewPager
中为第一个类别(包含3个问题)填充问题片段,但是当我从列表中选择另一个类别(包含5个问题)时,我无法替换前三个{{1 }}。它只是在Fragment
中添加了最后两个问题。我想用新的数据集重新填充ViewPager
。我已添加以下代码。
QuestionFragmentActivity
ViewPager
QuestionContainer.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions_activity);
if (findViewById(R.id.question_section_fragment_container) != null) {
/*
* if (getIntent().getExtras() != null) { return; }
*/
QuestionSection firstFragment = new QuestionSection();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager()
.beginTransaction()
.add(R.id.question_section_fragment_container,
firstFragment).commit();
}
categoryPosition = 0;//static variable to hold the position of category item selected.
CategoryVO cvo = QuestionFragmentActivity.categoryList
.get(categoryPosition);
if (findViewById(R.id.question_fragment_container) != null) {
/*
* if (getIntent().getExtras() != null) { return; }
*/
QuestionContainer firstFragment = new QuestionContainer();
firstFragment.setCvo(cvo);
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager()
.beginTransaction()
.add(R.id.question_fragment_container,
firstFragment).commit();
}
}
QuestionSection
public class QuestionContainer extends Fragment {
ViewPager mPager;
CategoryVO cvo;
public CategoryVO getCvo() {
return cvo;
}
public void setCvo(CategoryVO cvo) {
this.cvo = cvo;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_container, container,
false);
ArrayList<QuestionFragment> fragmentList=new ArrayList<QuestionFragment>();
for(QuestionVO qvo: cvo.getQuestionList()){
fragmentList.add(new QuestionFragment(qvo));
}
mPager = (ViewPager) view.findViewById(R.id.question_viewpager);
MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager());
mAdapter.setFragmentList(fragmentList);
mPager.setAdapter(mAdapter);
return view;
}
public static class MyAdapter extends FragmentPagerAdapter {
ArrayList<QuestionFragment> fragmentList;
public ArrayList<QuestionFragment> getFragmentList() {
return fragmentList;
}
public void setFragmentList(ArrayList<QuestionFragment> fragmentList) {
this.fragmentList = fragmentList;
}
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
答案 0 :(得分:1)
ViewPager.setAdapter(pager_adapter)
强制重绘ViewPager。首先进行适当的更改,然后执行此操作以进行刷新。
编辑: Adapter.notifyDataSetChanged()使现有数据无效以准备新数据。如果你到现在为止还没有使用它,那就去研究一下。