Roman Nurik's WizardPager inside Fragment - android

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

Related

how to fix" 3 fragment in One activity with viewPager need validation first two page then possible to go third page"

I want to create a createOrderActivity where has three fragments like Service info, ScheduleInfo, confirmation
the service info fragment has editText
if click NextButton(which is situated CreateOrderActivity) check validation editText first. then move ScheduleFragment page.
if first two pages validation ok then move to Confirmation Fragment page.
Here is the FragmentViewpagerAdapter class
public class FragmentViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public FragmentViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
In CreateOrderActivity class
#Override
public void onPageSelected(int position) {
boolean checkSch= false;
if (position == 1) {
ServiceInfoFragment serviceInfoFragment = new ServiceInfoFragment();
//checking validation from ServiceInfoFragment fragment Class
if (serviceInfoFragment.checkServiceValidation()) {
checkSch = true;
//Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
}else {
checkSch = false;
// Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-1);
}
}
if (position == 2) {
if (checkSch){
ScheduleFragment scheduleFragment = new ScheduleFragment();
if (scheduleFragment.checkScheduleValidation()) {
Toast.makeText(CreateOrderActivity.this, "Validation okay", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(CreateOrderActivity.this, "Please check S validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-1);
}
}else {
Toast.makeText(CreateOrderActivity.this, "Please check validation", Toast.LENGTH_SHORT).show();
pagerCreateOrder.setCurrentItem(position-2);
}
}
}
//checking checkScheduleValidation() in ScheduleFragment class. return null exception
*bellow mehtod declear in Fragment *
public boolean checkServiceValidation(){
return true;
}
I upload this Image
I used this Reference
I found a solution in my way. I have loaded three fragments in a viewpager. In the second fragment, there is one edittext. on clicking the next button, there is a validation for checking email. On the basis of validation next fragment is loaded. All the Fragments are loaded as singleton . You might have caused null pointer exception , because of multiple instance of fragments.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private FragmentTwo fragmentTwo;
private ViewPager mViewPager;
Button back, next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
back = findViewById(R.id.back);
next = findViewById(R.id.next);
next.setOnClickListener(this);
back.setOnClickListener(this);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.vp_viewpager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
if (i==2){
if (!fragmentTwo.checkEditText()) {
Toast.makeText(getApplicationContext(),"False",Toast.LENGTH_LONG).show();
mViewPager.setCurrentItem(i-1);
return;
}
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
private void changeViewPagerPosition(int position) {
int totalCount = mViewPager.getAdapter().getCount();
if (position < 0 || position >= totalCount) {
return;
}
mViewPager.setCurrentItem(position);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onClick(View view) {
int currentViewpagerPosition = mViewPager.getCurrentItem();
switch (view.getId()) {
case R.id.back:
changeViewPagerPosition(currentViewpagerPosition - 1);
break;
case R.id.next:
if (currentViewpagerPosition==1){
if (!fragmentTwo.checkEditText()) {
Toast.makeText(getApplicationContext(),"Falsee",Toast.LENGTH_LONG).show();
return;
}
}
changeViewPagerPosition(currentViewpagerPosition + 1);
break;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentOne.newInstance(position);
case 1:
return fragmentTwo=FragmentTwo.getInstance();
case 2:
return FragmentThree.newInstance(position);
default:
return FragmentThree.newInstance(position);
}
}
#Override
public int getCount() {
return 3;
}
}
}
The Fragment 2
public class FragmentTwo extends Fragment {
EditText email;
private static FragmentTwo fragment=null;
public FragmentTwo() {
}
public static FragmentTwo getInstance() {
if (fragment == null){
fragment = new FragmentTwo();
}
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
email = getView().findViewById(R.id.editText);
}
public boolean emailValidator()
{
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-" +
"9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email.getText().toString());
return matcher.matches();
}
public Boolean checkEditText(){
if (emailValidator()){
return true;
}
return false;
}
}

Null object reference when using getChildFragmentManager().beginTransaction()

I have 4 fragments in my ViewPgaer using FragmentPagerAdapter. I try to add each fragment after a constant delay to have a jerk free animation while switching bottom bar tabs.
I use this library for the bottom bar which has a shifting animation. All four fragments have multiple api calls and if I don't add these after a delay, the shifting animation is jerky.
The problem is I get an error log (posted below) which is hard to replicate.
Error Log:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:369)
at com.vanitee.services.view.FragmentFake$1.run(FragmentFake.java:46)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6585)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
ViewPagerAdapterClass:
class MyAccountPagerAdapter extends FragmentPagerAdapter {
public MyAccountPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == ME_TAB) {
if (Utility.isEmpty(fragmentProfile)) {
fragmentProfile = FragmentFake.create(new FragmentUserProfile(), 50);
}
return fragmentProfile;
} else if (position == BOOKINGS_TAB) {
if (Utility.isEmpty(fragmentBooking)) {
fragmentBooking = FragmentFake.create(new FragmentBookings(), 100);
}
return fragmentBooking;
} else if (position == WALLET_TAB) {
if (Utility.isEmpty(fragmentWallet)) {
fragmentWallet = FragmentFake.create(new FragmentWallet(), 150);
}
return fragmentWallet;
} else if (position == LIKES_TAB) {
if (Utility.isEmpty(fragmentLikes)) {
fragmentLikes = FragmentFake.create(new FragmentLikes(), 200);
}
return fragmentLikes;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case ME_TAB:
return getContext().getString(R.string.me_tab);
case BOOKINGS_TAB:
return getContext().getString(R.string.bookings_tab);
case WALLET_TAB:
return getContext().getString(R.string.wallet_tab);
case LIKES_TAB:
return getContext().getString(R.string.likes_tab);
default:
return null;
}
}
#Override
public int getCount() {
return 4;
}
}
FragmentFake:
public class FragmentFake extends Fragment {
private View root;
Fragment fragment;
public static Fragment create(Fragment frag, int timeMs) {
FragmentFake fragmentFake = new FragmentFake();
Bundle bundle = new Bundle();
fragmentFake.fragment = frag;
bundle.putInt("time", timeMs);
fragmentFake.setArguments(bundle);
return fragmentFake;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
root = inflater.inflate(R.layout.layout_fake_fragment, container, false);
Bundle bundle = getArguments();
replaceFragment(bundle.getInt("time"));
return root;
}
private void replaceFragment(int time) {
root.postDelayed(new Runnable() {
#Override
public void run() {
if(!isAdded()){
return;
}
getChildFragmentManager().beginTransaction().add(R.id.replace_fragment_container, fragment).commit();
}
}, time);
}
}
The Error log reported is on the line
getChildFragmentManager().beginTransaction().add(R.id.replace_fragment_container, fragment).commit();
Create one Abstract Fragment that extends Fragment. like this
public abstract BaseChildFragment extends Fragment{
public void onViewPagerPagechange();
}
Make All ChildFragment extends BaseChildFragment(FragmentUserProfile, FragmentUserLike,FragmentUserWellet,ETC) ,
On your Adapter add below code.
LruCache<Integer,BaseChildFragment> cache = new LruCache<>(4);
public BaseChildFragment getBaseChildFragment(int position){
return cache.get(position);
}
#Override
public Fragment getItem(int position) {
if (position == ME_TAB) {
if (Utility.isEmpty(fragmentProfile)) {
fragmentProfile = FragmentFake.create(new FragmentUserProfile(), 50);
cache.put(position,fragmentProfile );
}
return fragmentProfile;
} else if (position == BOOKINGS_TAB) {
if (Utility.isEmpty(fragmentBooking)) {
fragmentBooking = FragmentFake.create(new FragmentBookings(), 100);
cache.put(position,fragmentBooking );
}
return fragmentBooking;
} else if (position == WALLET_TAB) {
if (Utility.isEmpty(fragmentWallet)) {
fragmentWallet = FragmentFake.create(new FragmentWallet(), 150);
cache.put(position,fragmentWallet );
}
return fragmentWallet;
} else if (position == LIKES_TAB) {
if (Utility.isEmpty(fragmentLikes)) {
fragmentLikes = FragmentFake.create(new FragmentLikes(), 200);
cache.put(position,fragmentLikes );
}
return fragmentLikes;
}
return null;
}
On your Fragment that have View pager AddpageChangeListener like this
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
// optional
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
// optional
#Override
public void onPageSelected(int position) {
BaseChildFragment fragment = adapter.getBaseChildFragment(position);
fragmeng.onViewPagerPagechange();
}
// optional
#Override
public void onPageScrollStateChanged(int state) { }
});
This will call your ChildFragment onViewPagerPagechange(); method. where you can load your child fragments.
You cannot do this
public static Fragment create(Fragment frag, int timeMs) {
FragmentFake fragmentFake = new FragmentFake();
Bundle bundle = new Bundle();
//remove this line, it won't work
fragmentFake.fragment = frag;
bundle.putInt("time", timeMs);
fragmentFake.setArguments(bundle);
return fragmentFake;
}
You can remove that assignment line from the create statement and add another method to assign the fragment after an instance is created. Your code should be like this
public static Fragment create(Fragment frag, int timeMs) {
FragmentFake fragmentFake = new FragmentFake();
Bundle bundle = new Bundle();
bundle.putInt("time", timeMs);
fragmentFake.setArguments(bundle);
return fragmentFake;
}
public void setFragment(Fragment fragment){
this.fragment = fragment;
}
//How you assign fragment
FragmentFake fakeFragment = FragmentFake.create(0);
fakeFragment.setFragment(yourFragment);
Then make the fragment transaction

Android Load more Listview in ViewPager adapter

I have ViewPager with 4 pages in my Fragment and Inflating the ListView in pager adapter and it is working fine, now i implemented Load More for the ListView and Load More is working only for the first time automatically when ListView item scrolls end but from the second time on words it is not working when ListView item scrolls end.Please any on help me out on this :).
Following is the code where i implemented load more in my PagerAdapter.
#Override
public Object instantiateItem(ViewGroup container, int position)
{
final View view = getActivity().getLayoutInflater().inflate(R.layout.world_fragment_list, container, false);
listview = (LoadMoreListView) view.findViewById(R.id.listView);
listview.setAdapter(wfadapter);
listview.setOnLoadMoreListener(new LoadMoreListView.OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("Calling: ", "onLoadMore()");
}
}
});
container.addView(view);
return view;
}
I followed this tutorial and i resolved above problem.
Thanks #meynety for Helping me.
I do this in many of project and it's work very fine :
first create your ViewPager class with following code :
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance() {
return new CategoryFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_category, container, false);
initViews(rootView);
return rootView;
}
private void initViews(View rootView) {
ViewPager mPager = (ViewPager) rootView.findViewById(R.id.vp_pager);
mPager.setOffscreenPageLimit(4);
CategoryAdapter mAdapter = new CategoryAdapter(getChildFragmentManager());
mPager.setAdapter(mAdapter);
PagerSlidingTabStrip mIndicator = (PagerSlidingTabStrip) rootView.findViewById(R.id.vp_indicator);
mIndicator.setTypeface(FontHelper.getInstance(getActivity()).getPersianTextTypeface(), 0);
mIndicator.setViewPager(mPager);
}
private class CategoryAdapter extends FragmentPagerAdapter {
public CategoryAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return AllCategoryFragment.newInstance();
case 1:
return LatestVideoFragment.newInstance();
case 2:
return PopularVideoFragment.newInstance();
default:
return MostLikeVideoFragment.newInstance();
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return getResources().getString(R.string.drawer_title_category);
case 1:
return getResources().getString(R.string.drawer_title_latest_video);
case 2:
return getResources().getString(R.string.drawer_title_popular_video);
default:
return getResources().getString(R.string.drawer_title_most_liked_video);
}
}
}
}
Then create your BaseFragment class ( here I just put one of them ) :
public abstract class BaseListFragment extends Fragment implements AdapterView.OnItemClickListener {
protected boolean loadingMore, callingRequest ,isVisibleHint, firstRequest = true;
private PagingListView mListView;
private ProgressView mCircularProgress;
private ProgressView mLinearProgress;
private CustomPage mCustomPage;
private BaseListAdapter mAdapter;
private int mPageRequest = 1;
public abstract String getType();
public abstract String getCategorySlug();
public abstract String getCategoryId();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_base_list, container, false);
initViews(rootView);
if (isVisibleHint && firstRequest) {
firstRequest = false;
enable();
}
return rootView;
}
protected void initViews(View rootView) {
mLinearProgress = (ProgressView) rootView.findViewById(R.id.pvl_loading);
mCircularProgress = (ProgressView) rootView.findViewById(R.id.pvc_loading);
mCircularProgress.start();
mListView = (PagingListView) rootView.findViewById(R.id.lv_paging);
mAdapter = new BaseListAdapter(getActivity());
mListView.setOnItemClickListener(this);
}
public void performSearch() {
callingRequest = true;
if (!loadingMore) {
if (mCircularProgress != null)
mCircularProgress.start();
mCustomPage.setVisibility(View.GONE);
if (mAdapter != null)
mAdapter.removeAllItems();
mPageRequest = 1;
}
if (mPageRequest > 1) {
mLinearProgress.start();
}
ServiceHelper.getInstance().searchQuery(getCategoryId(), getCategorySlug(), null, null, getType(), null, mPageRequest).enqueue(new Callback<List<ShortVideoModel>>() {
#Override
public void onResponse(Response<List<ShortVideoModel>> response) {
callingRequest = false;
processResponse(response);
}
#Override
public void onFailure(Throwable t) {
processResponse(null);
}
});
}
public void resetPerformSearch(boolean callService) {
loadingMore = false;
mPageRequest = 1;
if (callService)
performSearch();
}
private void enable() {
mListView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
loadingMore = true;
if (!callingRequest)
performSearch();
}
});
mListView.setAdapter(mAdapter);
mListView.setHasMoreItems(true);
}
private void processResponse(Response<List<ShortVideoModel>> response) {
if (response != null && response.body() != null && response.body().size() > 0) {
mListView.onFinishLoading(true, response.body());
} else if (mPageRequest == 1) {
//show error
} else {
mListView.setHasMoreItems(false);
loadingMore = false;
}
mPageRequest++;
//stop loading
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(VideoDetailsActivity.createIntent(getActivity(), mAdapter.getItem(position).getId()));
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Log.d("Fragments", "fragment visible: " + getClass().getSimpleName());
isVisibleHint = true;
if (firstRequest && getView() != null) {
firstRequest = false;
enable();
}
}
}
}
Now Just create class which extend BaseFrgament;
You can Also take look at here to my LoadMoreListView

Call FragmentActivity from Fragment

Can I call a fragmentactivity from a fragment?
If I can call,how can it be done?
Otherwise, how can I solve this problem ?
In my code, I want to call FragmentWizard.class from the "FragmentMain" fragment,but this doesn't compile.
Below is my code:
public class FragmentMain extends Fragment {
TextView textView;
Button x;
public FragmentMain() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, null);
textView = (TextView) view.findViewById(R.id.fragment_main_textview);
x = (Button) view.findViewById(R.id.deneme);
x.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent firstpage= new Intent(getActivity(),FragmentWizard.class);
startActivity(firstpage);
}
});
return view;
}
}
FragmentWizard.java
public class FragmentWizard extends FragmentActivity implements
PageFragmentCallbacks, ReviewFragment.Callbacks, ModelCallbacks {
private ViewPager mPager;
private MyPagerAdapter mPagerAdapter;
private boolean mEditingAfterReview;
private AbstractWizardModel mWizardModel = new SandwichWizardModel(this);
private boolean mConsumePageSelectedEvent;
private Button mNextButton;
private Button mPrevButton;
private List<Page> mCurrentPageSequence;
private StepPagerStrip mStepPagerStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mWizardModel.load(savedInstanceState.getBundle("model"));
}
mWizardModel.registerListener(this);
mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mPagerAdapter);
mStepPagerStrip = (StepPagerStrip) 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) findViewById(R.id.next_button);
mPrevButton = (Button) 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(getSupportFragmentManager(), "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();
}
#Override
public void onPageTreeChanged() {
mCurrentPageSequence = mWizardModel.getCurrentPageSequence();
recalculateCutOffPage();
mStepPagerStrip.setPageCount(mCurrentPageSequence.size() + 1); // + 1 =
// review
// step
mPagerAdapter.notifyDataSetChanged();
updateBottomBar();
}
private void updateBottomBar() {
int position = mPager.getCurrentItem();
if (position == mCurrentPageSequence.size()) {
mNextButton.setText(R.string.finish);
mNextButton.setBackgroundResource(R.drawable.finish_background);
mNextButton.setTextAppearance(this, R.style.TextAppearanceFinish);
} else {
mNextButton.setText(mEditingAfterReview ? R.string.review
: R.string.next);
mNextButton
.setBackgroundResource(R.drawable.selectable_item_background);
TypedValue v = new TypedValue();
getTheme().resolveAttribute(android.R.attr.textAppearanceMedium, v,
true);
mNextButton.setTextAppearance(this, 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;
}
......
}
}
use getActivity() method. Which will return the enclosing activity for the fragment.
Intent firstpage= new Intent(getActivity(),FragmentWizard.class);
getActivity().startActivity(firstpage); // You same startActivity method in fragment as well you can use any of this
public final Activity getActivity ()
You have to use onActivityCreated method to use that:
In your class, just do:
public class FragmentMain extends Fragment {
public FragmentMain() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main,container, false);
return view;
}
}
And immediately after that, use the onActivityCreated method:
Here's the code:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView textView = (TextView) getActivity().findViewById(R.id.fragment_main_textview);
Button x = (Button) getActivity().findViewById(R.id.deneme);
x.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent firstpage= new Intent(getActivity(),FragmentWizard.class);
getActivity().startActivity(firstpage);
}
});
}
Hope this works..:)

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

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());
}
}
}

Categories

Resources