我正在开发一个 android java 应用程序,它就像一个包含 100 多个问题的调查。用户可以一次看到每个问题,所以对于每个问题,我都会制作一个一个一个通过的片段,我们称之为 QuestionFragment 有时,当用户提出第 50 个问题时,应用程序会崩溃并出现问题。好像是内存问题。我创建片段的方式是这段代码:
QuestionFragment nvofrag = new QuestionFragment(nvoReac,false);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.continf_fragment, nvofrag);
fragmentTransaction.commit();
这段代码在 QuestionFargment 中,它在“下一个问题”按钮中被调用,所以问题是我是否正确创建了片段?我的编程逻辑正确吗? 我希望清楚。任何想法或评论如何用谷歌搜索我的问题都可以寻求帮助。
我不知道我是否正确理解了你的问题,我不知道你是否有 100 个片段,如果是这样,当然它会导致内存问题和性能问题,因为
Fragments
创建的数量。
我推荐的是只有一个
Fragment
用于调查,并根据数据源、JSON 等动态填充问题,Fragment
里面有一个 ViewPager
或 RecyclerView
。
在
Activity
创建你的实例ViewPager
ViewPager viewPager = findViewById(R.id.viewPager);
QuestionPagerAdapter adapter = new QuestionPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
那你的
QuestionPagerAdapter
应该是这样的
@Override
public Fragment getItem(int position) {
QuestionFragment fragment = new QuestionFragment();
fragment.setQuestion(questionList.get(position));
return fragment;
}
@Override
public int getCount() {
return questionList.size(); //Assuming you have a list of questions
}
然后在你的单
Fragment
有一个setQuestion
的方法
public void setQuestion(Question question) {
this.question = question;
}
然后在
onCreateView
中执行逻辑以显示Question
并转到下一个问题
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_question, container, false);
logicToPrintQuestion();
//logic to change the question
nextButton.setOnClickListener(....)
//Here add the answer to a list if you want
//Using the viewPager to change the
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
return view;
}
这可能无法编译,但它是如何实现一个可能实现的想法。