Reputation: 939
I have a ViewPager with three tabs. One of tabs (fragments actually) contains EditText
.
Here's the problem: When I swipe to that fragment (when it is in focus) I want to show keyboard and when I swipe to next tab I want to hide keyboard. Problem is that in ViewPager
, fragment is destroyed only after i swipe to the third fragment, what means that keyboard stays open when a fragment without EditText
is in focus. And another problem is that, when I swipe from third fragment to second (which, I repeat, don't have EditText
control) keyboard shows because ViewPager
instantiate two fragments in a row. I hope that I'm clear enough, if not I will try to explain it. Is there some way to instantiate fragment in ViewPager
only when he comes in focus and save his state when its focused? Thanks...
EDIT
Here is my adapter:
public class TabPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public TabPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
fragments.get(position);
}
@Override
public int getCount() {
return this.fragments.size();
}
}
Upvotes: 0
Views: 2262
Reputation: 10785
Is there some way to instantiate fragment in ViewPager only when he comes in focus and save his state when its focused?
yes, there is. actually, PagerAdapter
has callback method - setPrimaryItem. according to the documentation:
Called to inform the adapter of which item is currently considered to be the "primary", that is the one show to the user as the current page.
it working pretty well and as expected, and I'm using it myself for a while exactly from the reason you described - showing/hiding keyboard for relevant page..
about saving the state - nothing prevent you from holding array of objects from any data structure you wish, that each one of them will hold fields that representing item in a specific position within the adapter.
EDIT
you should use the setPrimaryItem callback like this:
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
//assuming fragment in position 0 suppose to show keyboard, and others not.
if (position == 0) {
showKeyboardExplicitly();
} else {
hideKeyboardExplicitly();
}
}
Upvotes: 2