ViewPager + FragmentStatePagerAdapter: How to recreate all fragment with new adapter - android

I'm using the v4 compatibility library. I have a Fragment Tabhost, the first tab have a ViewPager using FragmentStatePagerAdapter. The problem is when I switch to other tabs, change data of the first tab's ViewPager, then return to the first tab, recreate new Adapter with new data and set it to ViewPager, but the first 3 fragments in ViewPager still hold reference to old data.
My code in the first tab to create adapter (called in onCreateView method):
private void setPagerData() {
if (mPager == null || AppConfig.getInstance().todayData == null)
return;
if (AppConfig.getInstance().todayData != null && !AppConfig.getInstance().todayData.isEmpty()) {
//
mPager.setOffscreenPageLimit(AppConfig.PAGER_OFFSCREEN_PAGE_LIMIT);
mPager.setAlwaysDrawnWithCacheEnabled(true);
//
mAdapter = new TodayPagerAdapter(getChildFragmentManager(), AppConfig.getInstance().todayData);
mPager.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
if (mAdapter.getCount() == 1)
mPager.setCurrentItem(0);
else
mPager.setCurrentItem(1);
text_currentpage.setText("1");
text_totalpage.setText(String.valueOf(mAdapter.getCount() - 2));
anim_numpage = AnimationUtils.loadAnimation(TodayFragment.this.getActivity(), R.anim.fade_numpage);
layout_numpage.setVisibility(View.INVISIBLE);
image_nextpage.setOnClickListener(this);
image_prevpage.setOnClickListener(this);
//
mPager.setOnPageChangeListener(this);
} else
onNoData(true);
}
onDestroyView():
public void onDestroyView() {
AppUtils.Log("Destroy view Today Fragment");
mAdapter = null;
mPager = null;
super.onDestroyView();
}
My Adapter:
public class TodayPagerAdapter extends FragmentStatePagerAdapter {
private List<PostDTO> posts;
private FragmentManager fm;
public TodayPagerAdapter(FragmentManager fm, List<PostDTO> posts) {
super(fm);
this.fm = fm;
this.posts = posts;
if (posts == null)
posts = new ArrayList<PostDTO>();
}
#Override
public Fragment getItem(int page) {
if (page == 0 && posts.size() > 1)
return TodayPagerFragment.init(posts.size() - 1, posts.get(posts.size() - 1));
if (page == posts.size() + 1)
return TodayPagerFragment.init(0, posts.get(0));
if (posts.size() > 1)
return TodayPagerFragment.init(page - 1, posts.get(page - 1));
return TodayPagerFragment.init(page, posts.get(page));
}
#Override
public int getCount() {
if (posts.size() <= 1)
return posts.size();
return posts.size() + 2;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
My ViewPager's Fragment:
public class TodayPagerFragment extends AbstractFragment implements View.OnClickListener {
int page;
private ImageView iv_image;
private LikeButton button_like;
private PostDTO data;
public static TodayPagerFragment init(int val, PostDTO data) {
TodayPagerFragment frm = new TodayPagerFragment();
Bundle args = new Bundle();
args.putInt("page", val);
frm.setArguments(args);
frm.data = data;
return frm;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments() != null ? getArguments().getInt("page") : 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_today_viewpager, container, false);
setupView(view);
iv_image = (ImageView) view.findViewById(R.id.today_viewpager_image);
button_like = (LikeButton) view.findViewById(R.id.today_button_like);
button_like.setUp(true);
initViews();
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.today_viewpager_image:
((BaseContainerFragment) getParentFragment().getParentFragment()).replaceFragment(TodayDetailFragment.init(this.data), true);
break;
case R.id.today_button_like:
if (!AppConfig.getInstance().isLoggedIn || AppConfig.getInstance().appUser == null) {
AppUtils.openLogin(getActivity());
} else {
String ms = getString(R.string.do_you_want_to_like_this_post_);
if (data.isLiked())
ms = getString(R.string.do_you_want_to_unlike_this_post_);
new MyDialogHandler().confirm(getActivity(), getString(R.string.like_confirm), ms, getString(R.string.no), getString(R.string.yes), new Runnable() {
#Override
public void run() {
new PostLikeTask(button_like, data, !data.isLiked()).execute();
// data.setLiked(!data.isLiked());
}
}, null);
}
break;
default:
break;
}
}
// Setup view data
private void initViews() {
iv_image.setOnClickListener(this);
button_like.setOnClickListener(this);
if (this.data != null) {
AppUtils.Log("Current: //////// " + (data.toString().equals(AppConfig.getInstance().todayData.get(page))));
// if (AppConfig.getInstance().appUser != null &&
// AppConfig.getInstance().isLoggedIn)
// new GetLikedTask().execute();
// else
button_like.setData(data.getLikes(), data.isLiked());
// ImageLoader.getInstance().displayImage(AppConfig.SERVER_IMAGE_URL
// + this.data.getImage(), iv_image);
// onLoading(true);
UrlImageViewHelper.setUrlDrawable(iv_image, AppConfig.SERVER_IMAGE_URL + this.data.getImage());
}
}
}

Related

Refresh a fragment inside a viewpager which is inside a fragment

I have an activity which consists of three fragments. In one of these fragments I have a viewpager that consists of three other fragments. I call getChildFragmentManager() inside fragment that has viewpager in it. I have searched SO and read almost every answer that are related to this topic for example: this and this and one that seemed most useful was this but could not solve my problem. I think if i can just return POSITION_NONE for getItemPosition(Object object) in FragmentStatePagerAdapter and call notifyDataSetChanged() will solve my problem but every time I do this my app crashes with this error:
java.lang.IllegalStateException: FragmentManager is already executing
transactions!!!
and I mentioned that I am using getChildFragmentManager() inside my fragment.
Anyone thinks of any solution to this problem?
this is the parent fragment:
public class WordDetailFragment extends Fragment {
#BindView(R.id.word_parts_tab_layout)
TabLayout mTabLayout;
#BindView(R.id.word_part_view_pager)
ViewPager mViewPager;
private WordPagerAdapter mPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
ButterKnife.bind(this, view);
mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
return view;
}
public void notifyTranslateChanged() {
mViewPager.getAdapter().notifyDataSetChanged();
}
}
this is the code for adapter
public class WordPagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 3;
private String[] tabTitles = new String[]{"Definition", "Example", "Col & fam"};
private Context context;
public WordPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case 0:
fragment = new WordDefinitionFragment();
break;
case 1:
fragment = new WordExampleFragment();
break;
case 2:
fragment = new WordColFamFragment();
break;
default: fragment = new WordDefinitionFragment();
}
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
One of the fragments in viewpager
public class WordDefinitionFragment extends Fragment {
#BindView(R.id.show_translate_switch)
Switch mShowTranslateSwitch;
private List<WordInfo> mWordInfoList;
private List<Definition> mDefinitionList;
private boolean mShowTranslation;
private View mView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_word_definition, container, false);
ButterKnife.bind(this, mView);
mShowTranslation = SharedPrefHelper.getBooleanInfo(getActivity(), getString(R.string.show_translate_key));
mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (getActivity() != null)
((WordActivity) getActivity()).changeTranslateMode(b);
showTranslation(b);
}
});
return mView;
}
}
and my activity. U have just included the parts that i felt are needed here.
public class WordActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceSate) {
super.onCreate(savedInstanceSate);
setContentView(R.layout.activity_word);
}
public void changeTranslateMode(boolean show) {
SharedPrefHelper.setBooleanInfo(this, getString(R.string.show_translate_ke)y, show);
((WordDetailFragment)mWordDetailFragment).notifyTranslateChanged();
}
}
and my logcat error is
After many searches I could figure out a way which is not very smart but for the time being has solved my problem.
First of all I used the class FixedFragmentStatePagerAdapter from this post. I also had to remove the part in which the fragment bundle is restored because it caches fragment variables and views.
public abstract class FixedFragmentStatePagerAdapter extends PagerAdapter {
private static final String TAG = "PagerAdapter";
private static final boolean DEBUG = false;
private final FragmentManager mFragmentManager;
private FragmentTransaction mCurTransaction = null;
private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<>();
private ArrayList<String> mSavedFragmentTags = new ArrayList<>();
private ArrayList<Fragment> mFragments = new ArrayList<>();
private Fragment mCurrentPrimaryItem = null;
public FixedFragmentStatePagerAdapter(FragmentManager fm) {
mFragmentManager = fm;
}
/**
* Return the Fragment associated with a specified position.
*/
public abstract Fragment getItem(int position);
public String getTag(int position) {
return null;
}
#Override
public void startUpdate(ViewGroup container) {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// If we already have this item instantiated, there is nothing
// to do. This can happen when we are restoring the entire pager
// from its saved state, where the fragment manager has already
// taken care of restoring the fragments we previously had instantiated.
if (mFragments.size() > position) {
Fragment f = mFragments.get(position);
if (f != null) {
return f;
}
}
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
Fragment fragment = getItem(position);
String fragmentTag = getTag(position);
if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " t=" + fragmentTag);
/* if (mSavedState.size() > position) {
String savedTag = mSavedFragmentTags.get(position);
if (TextUtils.equals(fragmentTag, savedTag)) {
Fragment.SavedState fss = mSavedState.get(position);
if (fss != null) {
fragment.setInitialSavedState(fss);
}
}
}*/
while (mFragments.size() <= position) {
mFragments.add(null);
}
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
mFragments.set(position, fragment);
mCurTransaction.add(container.getId(), fragment, fragmentTag);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}
if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
+ " v=" + ((Fragment)object).getView() + " t=" + fragment.getTag());
while (mSavedState.size() <= position) {
mSavedState.add(null);
mSavedFragmentTags.add(null);
}
mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
mSavedFragmentTags.set(position, fragment.getTag());
mFragments.set(position, null);
mCurTransaction.remove(fragment);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment)object;
if (fragment != mCurrentPrimaryItem) {
if (mCurrentPrimaryItem != null) {
mCurrentPrimaryItem.setMenuVisibility(false);
mCurrentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
}
mCurrentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(ViewGroup container) {
if (mCurTransaction != null) {
mCurTransaction.commitAllowingStateLoss();
mCurTransaction = null;
mFragmentManager.executePendingTransactions();
}
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment)object).getView() == view;
}
#Override
public Parcelable saveState() {
Bundle state = null;
if (mSavedState.size() > 0) {
state = new Bundle();
Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
mSavedState.toArray(fss);
state.putParcelableArray("states", fss);
state.putStringArrayList("tags", mSavedFragmentTags);
}
for (int i=0; i<mFragments.size(); i++) {
Fragment f = mFragments.get(i);
if (f != null) {
if (state == null) {
state = new Bundle();
}
String key = "f" + i;
mFragmentManager.putFragment(state, key, f);
}
}
return state;
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
if (state != null) {
Bundle bundle = (Bundle)state;
bundle.setClassLoader(loader);
Parcelable[] fss = bundle.getParcelableArray("states");
mSavedState.clear();
mFragments.clear();
ArrayList<String> tags = bundle.getStringArrayList("tags");
if (tags != null) {
mSavedFragmentTags = tags;
} else {
mSavedFragmentTags.clear();
}
if (fss != null) {
for (int i=0; i<fss.length; i++) {
mSavedState.add((Fragment.SavedState)fss[i]);
}
}
Iterable<String> keys = bundle.keySet();
for (String key: keys) {
if (key.startsWith("f")) {
int index = Integer.parseInt(key.substring(1));
Fragment f = mFragmentManager.getFragment(bundle, key);
if (f != null) {
while (mFragments.size() <= index) {
mFragments.add(null);
}
f.setMenuVisibility(false);
mFragments.set(index, f);
} else {
Log.w(TAG, "Bad fragment at key " + key);
}
}
}
}
}
}
Then I implemented ViewPager.OnPageChangeListener in the fragment that contains the viewpager. And in the void onPageScrollStateChanged(int state) method I updated the view of my fragments in viewpager.
public class WordDetailFragment extends Fragment implements ViewPager.OnPageChangeListener {
#BindView(R.id.word_parts_tab_layout)
TabLayout mTabLayout;
#BindView(R.id.word_part_view_pager)
ViewPager mViewPager;
private WordPagerAdapter mPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_word_detail, container, false);
ButterKnife.bind(this, view);
mPagerAdapter = new WordPagerAdapter(getChildFragmentManager(), getActivity());
mViewPager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(this);
return view;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
Fragment mFragment;
#Override
public void onPageSelected(int position) {
mFragment = mPagerAdapter.getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (mFragment instanceof WordDefinitionFragment) {
((WordDefinitionFragment) mFragment).showTranslation();
//Log.e("StateChanged", mFragment.getClass().getSimpleName());
}
if (mFragment instanceof WordExampleFragment) {
((WordExampleFragment) mFragment).showTranslation();
//Log.e("StateChanged", mFragment.getClass().getSimpleName());
}
if (mFragment instanceof WordColFamFragment) {
((WordColFamFragment) mFragment).showTranslation();
//Log.e("StateChanged", mFragment.getClass().getSimpleName());
}
}
}
}
And in my fragments, I had a callback interface which was implemented in the activity. And in void setUserVisibleHint(boolean isVisibleToUser) method I updated the UI again because neighbor fragments did not get updated.
public class WordExampleFragment extends Fragment {
#BindView(R.id.example_field_name_id)
TextView mExampleFieldNameTV;
#BindView(R.id.word_tv)
TextView mWordTv;
#BindView(R.id.play_sound_iv)
ImageView mPlaySoundIv;
#BindView(R.id.show_translate_switch)
Switch mShowTranslateSwitch;
private TextView mExample1ContentFaTV;
private List<WordInfo> mWordInfoList;
private List<Example> mExampleList;
private int mWordNumber;
//callback interface
private TranslateModeChangeListener mWordPartFragments;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mWordPartFragments = (TranslateModeChangeListener) context;
} catch (ClassCastException ex) {
throw new ClassCastException("Must implement WordPartFragments interface");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_word_example, container, false);
ButterKnife.bind(this, view);
mWordInfoList = WordActivity.sWordInfoList;
mWordNumber = WordActivity.sWordNumber;
mExampleList = mWordInfoList.get(mWordNumber).getExamples();
showTranslation();
mShowTranslateSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//this method is called from activity=> callback interface
mWordPartFragments.changeTranslateMode(b);
showTranslation();
}
});
return view;
}
//this method is called when viewpager shows this fragment and it is visible to user
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
showTranslation();
}
}
//this methoud updates my UI: shows or hides the translation
public void showTranslation() {
if (isAdded()) {
boolean showTranslation = WordActivity.sTranslationShown;
//Log.e("Ex", "added & shown = " + showTranslation);
mShowTranslateSwitch.setChecked(showTranslation);
mExample1ContentFaTV.setVisibility((showTranslation) ? View.VISIBLE : View.INVISIBLE);
}
}
}

Fragment disappearing when coming back from another Fragment

I have a viewpager with 3 fragments to make a swipeable widget. When I first load the app they show properly and all the click events work as expected. Same with hitting the back button after clicking each OnClick, sends me back to landingpagenotlogged in and the viewpager/fragments are displayed as expected. My problem is when I hit my menu button and come back to the landing page my view pager disappears.
I did try to use getChildFragmentManager() when setting the adapter and it works but then my onClick events do not work any more as I get no view to id *******.
I have also tried to place the adapter in the onResume(); with no luck at all.
Along with the viewpager, my viewpagerindicator is not working for the homewidget but working for the carousel. Not sure if that is the code or the layout. But I set it up the same way as the carousel and still not seeing it within the screen when run.
Landingpagenotlogged
public class LandingPageFragmentLoggedOut extends LandingPageFragment {
private static final String TAG = LandingPageFragmentLoggedOut.class.getSimpleName();
private ViewPager viewPager;
private RelativeLayout myStoreTab;
private Button signIn;
private final static Fragment instance = new LandingPageFragmentLoggedOut();
LoggedOutWidgetAdapter mAdapter;
ViewPager mPager;
public static final int ITEMS = 3;
static public Fragment getInstance() {
return instance;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
setShoppingListFocusChangeListener();
setSignInBtnClickListener();
super.setViewPagerMotionListeners(viewPager);
setMenuTouchListener();
setTabClickListener();
return view;
}
#Override
protected void inflateFragmentView(LayoutInflater inflater, ViewGroup container) {
view = inflater.inflate(R.layout.landingpage_not_logged_in, container,
false);
RelativeLayout thisLayout = (RelativeLayout) view
.findViewById(R.id.landingpage_logged_out_parent_layout);
TileBackground.fixBackgroundRepeat(thisLayout);
imgArch = view.findViewById(R.id.frag_tab);
}
private void setSignInBtnClickListener() {
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> params = new HashMap<>();
Intent intent = new Intent(getActivity(), SignInActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(
R.anim.enter_in_from_bottom, R.anim.anim_static);
params.put("Module", "Home");
FlurryAgent.logEvent(FlurryConstants.GOTO_SIGN_IN, params);
}
});
}
private void setTabClickListener() {
myStoreTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tabSelection = 1;
tabSelectionListener.onTabSelectionListener(tabSelection);
toggleStoreTabIndicator(1);
}
});
}
#Override
#SuppressLint("WrongViewCast")
protected void setUIreferences() {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
overlay = view.findViewById(R.id.landingpage_screenOverlay);
indicator = (LinePageIndicator) view.findViewById(R.id.image_slider_indicator);
this.signIn = (Button) view.findViewById(R.id.landingpg_sign_in_btn);
shoppingListBtn = (ImageView) view.findViewById(R.id.icnlistoptions);
myStoreTab = (RelativeLayout) view.findViewById(R.id.frag_tab);
menuButton = (Button) view.findViewById(R.id.imgBanner_list);
logoButton = (ImageView) view.findViewById(R.id.headerLogo);
addShoppingListItemWidget = (EditText) view.findViewById(R.id.editAddItemNotLoggedIn);
addShoppingListItemWidget.setOnKeyListener(null);
addedItemConfirmation = view.findViewById(R.id.addedItemConfirmation);
imgScanner = (ImageView) view.findViewById(R.id.imgScannerNotLoggedIn);
toggleScannerVisibility(true);
itemAddedText = (TextView) view.findViewById(R.id.item_added_text);
weeklyAdImg = (ImageView) view.findViewById(R.id.weeklyad_img);
defaultWelcomeMsg = (ImageView) view.findViewById(R.id.landing_page_default_img);
setWeeklyAdThumbNail();
if(imgUrl!=null)
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
//setWeeklyAdOnClickListener();
setWeeklyAdClickListener();
couponsGrid = view.findViewById(R.id.coupons_grid);
couponsPlaceholderImg = (ImageView) view.findViewById(R.id.feat_coupons);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
itemAddedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
}
imgScanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
mShoppingListAdd = (RelativeLayout) view.findViewById(R.id.shoppinglis_shortcut);
mShoppingListAdd.setVisibility(View.GONE);
mAdapter = new LoggedOutWidgetAdapter(getFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(mAdapter);
LinePageIndicator mLoggedOutWidgetIndicator = (LinePageIndicator)view.findViewById(R.id.homewidgetLoggedOutIndicator);
mLoggedOutWidgetIndicator.setViewPager(mPager);
}
// MSM - 214
private void setWeeklyAdThumbNail() {
try {
if (LocalDb.getStoreId() != LocalDb.DEFAULT_VAL) {
if (weeklyAdBundle != null && !weeklyAdBundle.isEmpty()) {
//MSM - 155
if (!Utils.isStringNull(weeklyAdBundle.getString("WeeklyAdThumbnail"))) {
Log.e("BANNER ID SET: ", weeklyAdBundle.getString("WeeklyAdThumbnail"));
imgUrl = weeklyAdBundle.getString("WeeklyAdThumbnail");
}
else
imgUrl = weeklyAdBundle.getString("0FirstThumbnail");
}
}
if (urls == null || !urls.contains(imgUrl)) {
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
}
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
jsonParser = new CarouselJSONParser(this);
jsonParser.execute();
} else {
setDefaultOfflineImage();
weeklyAdImg.setImageResource(R.drawable.img_ad_default);
// TODO Set OFFLINE message here
}
}
#Override
public void setCarouselData(ArrayList<CarouselImageData> imageDatas) {
Log.v(TAG, "Set Carousel Data hit");
if (imageDatas != null) {
this.advertisements = imageDatas;
runnable(advertisements.size());
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
viewPager
.setAdapter(new ImageSliderAdapter(activity, imageDatas, this, weeklyAdBundle));
indicator.setViewPager(viewPager);
if (isFirstTimeLaunched) {
fadeInWelcomMsg();
Log.v(TAG, "first time launched, welcome message initaited");
} else {
viewPager.setVisibility(View.VISIBLE);
indicator.setVisibility(View.VISIBLE);
Log.v(TAG, "Returning user, viewpager set visible");
}
} else {
setDefaultOfflineImage();
}
}
#Override
public void onResume() {
if (LocalDb.isLoggedIn()) {
Fragment fragment = new LandingPageFragment();
launchNavigationItemFragment(fragment);
}
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
if (viewPager == null) {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
}
mAdapter = new LoggedOutWidgetAdapter(getChildFragmentManager());
super.onResume();
if (newItemIsAdded) {
onShoppingListResult();
}
// addShoppingListItemWidget.clearFocus();
}
#Override
void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
#Override
public void run() {
if (!pageIsSliding) {
if (viewPager.getCurrentItem() == size - 1) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(
viewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
}
}
};
}
#Override
void toggleStoreTabIndicator(int tab) {
if (storeTabIsClosed) {
storeTabIsClosed = false;
imgArch.setBackgroundResource(R.drawable.img_single_arch_my_store);
} else {
storeTabIsClosed = true;
imgArch.setBackgroundResource(R.drawable.img_arch);
}
}
#Override
protected void setFontsOnTextViews(View view) {
}
#Override
protected void setTabClickListeners() {
}
#Override
public void setViewPagerMotionListeners(ViewPager vPager) {
}
public class LoggedOutWidgetAdapter extends FragmentPagerAdapter {
public LoggedOutWidgetAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ProductLocatorHomeWidgetFragment.init(position);
case 1:
return ProductScanHomeWidgetFragment.init(position);
case 2:
return MyShoppingListHomeWidgetFragment.init(position);
default:
return null;
}
}
#Override
public int getCount() {
return ITEMS;
}
}
}
The three fragments that are tied to the viewpager
ProductLocatorHomeWidgetFragment
public class ProductLocatorHomeWidgetFragment extends Fragment {
int fragVal;
int storeId;
String storeName, storeLat, storeLong, retail_store_id;
TextView mProductLocatorClickZone;
StoreList sList;
public static ProductLocatorHomeWidgetFragment init(int val) {
ProductLocatorHomeWidgetFragment productLocatorFragment = new ProductLocatorHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodLocator", val);
productLocatorFragment.setArguments(args);
return productLocatorFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("prodLocator") : 1;
sList = new StoreList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_locator_search_widget, container, false);
mProductLocatorClickZone = (TextView) layoutView.findViewById(R.id.editSearchItemNotLoggedIn);
mProductLocatorClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sList = LandingPageFragment.storeList;
if(sList.getId() != null){
storeId = Integer.parseInt(sList.getId());
storeLat = sList.getLatitude();
storeLong = sList.getLongitude();
storeName = sList.getName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
else if (sList.getId() == null) {
if (LocalDb.getStoreId() > 0) {
storeId = LocalDb.getStoreId();
storeLat = LocalDb.getStoreLat();
storeLong = LocalDb.getStoreLng();
storeName = LocalDb.getMyStoreName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
}
else {
StoreLocatorDetailsSearchFragment storeLocatorDetailsSearchFragment = new StoreLocatorDetailsSearchFragment();
Bundle b1 = new Bundle();
b1.putInt("currentFragment", 10);
storeLocatorDetailsSearchFragment.setArguments(b1);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, storeLocatorDetailsSearchFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return layoutView;
}
}
MyShoppingListHomeWidgetFragment
public class MyShoppingListHomeWidgetFragment extends Fragment {
int fragVal;
EditText mShoppingListClickZone;
ImageView mShoppinglistScanClickZone;
public static MyShoppingListHomeWidgetFragment init(int val) {
MyShoppingListHomeWidgetFragment myShoppingListFragment = new MyShoppingListHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("myShoppingList", val);
myShoppingListFragment.setArguments(args);
return myShoppingListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("myShoppingList") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.shopping_list_widget, container, false);
mShoppingListClickZone = (EditText) layoutView.findViewById(R.id.editAddItemNotLoggedIn);
mShoppingListClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingListItemsFragment shoppingListItemsFragment = new ShoppingListItemsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, shoppingListItemsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
mShoppinglistScanClickZone = (ImageView) layoutView.findViewById(R.id.imgScannerNotLoggedIn);
mShoppinglistScanClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
return layoutView;
}
}
ProductScanHomeWidgetFragment
public class ProductScanHomeWidgetFragment extends Fragment {
int fragVal;
LinearLayout mCouponSearchClickZone, mRefillPrescriptionClickZone;
View mDivider;
public static ProductScanHomeWidgetFragment init(int val) {
ProductScanHomeWidgetFragment productScanFragment = new ProductScanHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodScan", val);
productScanFragment.setArguments(args);
return productScanFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("prodScan") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_scan_widget, container, false);
mRefillPrescriptionClickZone = (LinearLayout) layoutView.findViewById(R.id.refillPrescriptionClickZone);
mCouponSearchClickZone = (LinearLayout) layoutView.findViewById(R.id.couponSearchClickZone);
mCouponSearchClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ECouponsViewFragment eCouponsViewFragment = new ECouponsViewFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, eCouponsViewFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
if (LocalDb.getBannerSupportRefillPrescriptions().equalsIgnoreCase(
UtilConstants.KEY_WORD_FALSE)) {
mDivider = layoutView.findViewById(R.id.divider);
mDivider.setVisibility(View.GONE);
mRefillPrescriptionClickZone.setVisibility(View.GONE);
} else {
mRefillPrescriptionClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPharmacyFragment addPharmacyFragment = new AddPharmacyFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, addPharmacyFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
return layoutView;
}
}
I was able to solve this using a FragmentStatePagerAdapter and not the FragmentPagerAdapter.
So I removed the old FragmentPagerAdapter in LadingPageLoggedOut and replaced it with
inal String [] fragmentClasses = {"com.supervalu.mobile.android.HomeScreenWidget.ProductLocatorHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.ProductScanHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.MyShoppingListHomeWidgetFragment"};
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// Check to make sure that your array is not null, size is greater than 0 ,
// current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});

How to destroy a Fragment programmatically in FragmentStatePagerAdapter

I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}

How does findFragmentByTag work in a parent Fragment to know which child fragment is currently showing with ViewPagerAdapter?

My MainFragment is like
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(3);
// changeTab();
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
pager.setCurrentItem(position_tab);
}
Log.e("Fragment", fragment + "" +pager.getCurrentItem());
//
return view;
}
public void changeTab(){
pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss" ,(Fragment) maps.get(position).get(KEY_FRAGMENT) +"");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
#Override
public int getCount() {
return maps.size();
}
}
}
Here I can get that this fragment is visible by using findFragmentByTag. I wanna know how I can use same thing for the child of this Fragment which are added using FragmentPagerAdapter.
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null){
Log.e("Fragment", fragment + "" +pager.getCurrentItem()); }
So now I wanna do same thing and get name of current selected Fragment out of 3 which are mentioned above in FragmentPagerAdapter as AdvisoryPagerFragment,TopAdvisoryPagerFragment and ExperViewPagerFragment.
Try this
Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if(fragment instanceOf Fragment1){
// Do something
}else if(fragment instanceOf Fragment2){
// Do something
}else{
// Do something
}

Roman Nurik's WizardPager inside Fragment

I have a FragmentActivity with different Fragments inside which can be switched through a NavigationDrawer.
Roman Nurik's original code was written with a FragmentActivity but I need it inside a Fragment...
This is my Activity (shortened):
public class MainActivity extends FragmentActivity implements
PageFragmentCallbacks, ReviewFragment.Callbacks, ModelCallbacks {
// those are the methods I took from the sample
#Override
public void onPageTreeChanged() {
mCurrentPageSequence = mWizardModel.getCurrentPageSequence();
recalculateCutOffPage();
mStepPagerStrip.setPageCount(mCurrentPageSequence.size() + 1); // + 1 =
// review
// step
mPagerAdapter.notifyDataSetChanged();
updateBottomBar();
}
private static void updateBottomBar() {
int position = mPager.getCurrentItem();
if (position == mCurrentPageSequence.size()) {
mNextButton.setText(R.string.finish);
mNextButton.setBackgroundResource(R.drawable.finish_background);
mNextButton.setTextAppearance(myContext,
R.style.TextAppearanceFinish);
} else {
mNextButton.setText(mEditingAfterReview ? R.string.review
: R.string.next);
mNextButton
.setBackgroundResource(R.drawable.selectable_item_background);
TypedValue v = new TypedValue();
myContext.getTheme().resolveAttribute(
android.R.attr.textAppearanceMedium, v, true);
mNextButton.setTextAppearance(myContext, v.resourceId);
mNextButton.setEnabled(position != mPagerAdapter.getCutOffPage());
}
mPrevButton
.setVisibility(position <= 0 ? View.INVISIBLE : View.VISIBLE);
}
#Override
protected void onDestroy() {
super.onDestroy();
mWizardModel.unregisterListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("model", mWizardModel.save());
}
#Override
public AbstractWizardModel onGetModel() {
return mWizardModel;
}
#Override
public void onEditScreenAfterReview(String key) {
for (int i = mCurrentPageSequence.size() - 1; i >= 0; i--) {
if (mCurrentPageSequence.get(i).getKey().equals(key)) {
mConsumePageSelectedEvent = true;
mEditingAfterReview = true;
mPager.setCurrentItem(i);
updateBottomBar();
break;
}
}
}
#Override
public void onPageDataChanged(Page page) {
if (page.isRequired()) {
if (recalculateCutOffPage()) {
mPagerAdapter.notifyDataSetChanged();
updateBottomBar();
}
}
}
#Override
public Page onGetPage(String key) {
return mWizardModel.findByKey(key);
}
private static boolean recalculateCutOffPage() {
// Cut off the pager adapter at first required page that isn't completed
int cutOffPage = mCurrentPageSequence.size() + 1;
for (int i = 0; i < mCurrentPageSequence.size(); i++) {
Page page = mCurrentPageSequence.get(i);
if (page.isRequired() && !page.isCompleted()) {
cutOffPage = i;
break;
}
}
if (mPagerAdapter.getCutOffPage() != cutOffPage) {
mPagerAdapter.setCutOffPage(cutOffPage);
return true;
}
return false;
}
}
This is my Fragment code:
public static class MyFragment extends Fragment {
public MyFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy3,
container, false);
if (savedInstanceState != null) {
mWizardModel.load(savedInstanceState.getBundle("model"));
}
mWizardModel.registerListener(this);
mPagerAdapter = new MyPagerAdapter(fragmentManager1);
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPager.setAdapter(mPagerAdapter);
mStepPagerStrip = (StepPagerStrip) rootView
.findViewById(R.id.strip);
mStepPagerStrip
.setOnPageSelectedListener(new StepPagerStrip.OnPageSelectedListener() {
#Override
public void onPageStripSelected(int position) {
position = Math.min(mPagerAdapter.getCount() - 1,
position);
if (mPager.getCurrentItem() != position) {
mPager.setCurrentItem(position);
}
}
});
mNextButton = (Button) rootView.findViewById(R.id.next_button);
mPrevButton = (Button) rootView.findViewById(R.id.prev_button);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mStepPagerStrip.setCurrentPage(position);
if (mConsumePageSelectedEvent) {
mConsumePageSelectedEvent = false;
return;
}
mEditingAfterReview = false;
updateBottomBar();
}
});
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mPager.getCurrentItem() == mCurrentPageSequence.size()) {
DialogFragment dg = new DialogFragment() {
#Override
public Dialog onCreateDialog(
Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setMessage(
R.string.submit_confirm_message)
.setPositiveButton(
R.string.submit_confirm_button,
null)
.setNegativeButton(
android.R.string.cancel, null)
.create();
}
};
dg.show(fragmentManager1, "place_order_dialog");
} else {
if (mEditingAfterReview) {
mPager.setCurrentItem(mPagerAdapter.getCount() - 1);
} else {
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
}
}
}
});
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
});
onPageTreeChanged();
updateBottomBar();
return rootView;
}
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private int mCutOffPage;
private Fragment mPrimaryItem;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
if (i >= mCurrentPageSequence.size()) {
return new ReviewFragment();
}
return mCurrentPageSequence.get(i).createFragment();
}
#Override
public int getItemPosition(Object object) {
if (object == mPrimaryItem) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
#Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
super.setPrimaryItem(container, position, object);
mPrimaryItem = (Fragment) object;
}
#Override
public int getCount() {
return 6;
// return Math.min(mCutOffPage + 1,
// mCurrentPageSequence.size() + 1);
}
public void setCutOffPage(int cutOffPage) {
if (cutOffPage < 0) {
cutOffPage = Integer.MAX_VALUE;
}
mCutOffPage = cutOffPage;
}
public int getCutOffPage() {
return mCutOffPage;
}
}
}
I get the following errors:
The method registerListener(ModelCallbacks) in the type AbstractWizardModel is not applicable for the arguments (MainActivity.MyFragment)
and:
Cannot make a static reference to the non-static method onPageTreeChanged() from the type MainActivity
What can I do to fix those errors?
Try changing:
registerListener(this)
for
registerListener(getActivity())
The other error, as you can read from the message, your fragment is static and you are calling onPageTreeChanged() that is in the MainActivity, which is not static. You could keep a reference to the MainActivity this way:
First in your Fragment declare a variable of type ModelCallbacks:
ModelCallbacks mModelCallback;
Then, override the Fragment's onAttach method, and set the reference:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mModelCallback = (ModelCallbacks)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ModelCallbacks");
}
}
Finally, instead of calling directly onPageTreeChanged() from the fragment, change the line for:
mModelCallback.onPageTreeChanged();
That should solve your errors.
This is most likely too late a response. But in case someone else falls victim of a similar issue:
Your fragment doesn't seem to implement the necessary callbacks. That explains the case where it wasn't applicable to the registerListener method.
You should implement these PageFragmentCallbacks, ReviewFragment.Callbacks, ModelCallbacks callbacks. Particularly, registerListener(ModelCallbacks) requires that whatever parameter you supply (your fragment in this case) implements the ModelCallbacks interface

Categories

Resources