#java #android #android-fragments
#java #Android #android-фрагменты
Вопрос:
У меня неприятная проблема. Я могу создавать каждый фрагмент, который обрабатывает адаптер пейджера, и я могу провести пальцем вправо, чтобы просмотреть их все; однако при пролистывании влево фрагменты либо исчезают, либо просто дублируют тот, который я уже просматривал. Я поискал в Google и не смог найти многого, что сбивает с толку, поскольку API для FragmentPagerAdapter говорит, что он хранит каждый фрагмент в памяти. Я буду отображать максимум около 20 фрагментов, поэтому память не является проблемой. В любом случае, вот мой код, и я ценю любую обратную связь, которую вы можете дать; он все еще находится на стадии предварительной альфа-версии.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_screen);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
}
/**
* TEMPORARY
*/
public void onBackPressed() {
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.events_screen, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
return EventFragment.newInstance(position 1);
}
/**
* Total number of pages (fragments) there are
* Given by size of the array returned by Service.getEvents()
*/
@Override
public int getCount() {
return connection.getEvents().size();
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
/**
* The fragment holding the text for each event.
*/
public static class EventFragment extends Fragment {
static int index;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static EventFragment newInstance(int sectionNumber) {
index = sectionNumber;
EventFragment fragment = new EventFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_events_screen, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(connection.getEvents().get(index - 1));
return rootView;
}
}
Ответ №1:
Да, вы правы фрагменты хранятся в памяти, но он будет использовать большой объем памяти, что дает не ожидаемый результат, который вы хотите, как говорится в документации:
Фрагмент каждой страницы, которую посещает пользователь, будет сохранен в памяти, хотя его иерархия представлений может быть уничтожена, когда она не видна. Это может привести к использованию значительного объема памяти, поскольку экземпляры фрагментов могут сохранять произвольное количество состояний. Для больших наборов страниц рассмотрите FragmentStatePagerAdapter .
FragmentStatePagerAdapter — это тот, который вы ищете, если хотите иметь много страниц / фрагментов в адаптере.
Комментарии:
1. Считается ли ~ 15-20 большим количеством страниц / фрагментов? Все, что он показывает, это некоторый текст. Я сомневаюсь, что это проблема с памятью.
2. Хорошо, тогда я посмотрю на вашу ссылку. Спасибо.
Ответ №2:
При использовании FragmentStatePagerAdapter я смог решить две проблемы:
1) Повторяющиеся фрагменты, которые, к сожалению, исчезли, когда я провел пальцем вправо и влево. Это произошло из-за того, что GetItem() дважды вызывал один и тот же фрагмент из-за EventFragment.newInstance(позиция 1).
2) Сохраните состояние экземпляра фрагментов, чтобы я мог постоянно прокручивать влево и вправо, не натыкаясь на пустую страницу.
Спасибо за вашу помощь, @Rod_Algonquin. Сэкономил мне часы стресса.