ViewPager数据从下一个屏幕返回时丢失

我在我的应用程序中使用ViewPager,我有三个选项卡; 我在片段中使用ViewPager。 现在我的问题是,我正在加载应用程序正确的数据,但是当我去下一页,然后回到ViewPager,数据丢失,标签不工作。 请帮助我 以下是我的代码:

import com.devpoint.rprtjobs.R; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTabHost; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.design.widget.TabLayout; public class MainActivity extends Fragment { // Declaring Your View and Variables Toolbar toolbar; ViewPager pager; SwipeViewPagerAdapter adapter; SlidingTabLayout tabs; CharSequence Titles[]={"OnGoing","UpComing","Expired"}; int Numboftabs =3; private View rootView; @SuppressWarnings("deprecation") public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { rootView = inflater.inflate(R.layout.activity_main, container, false); adapter = new SwipeViewPagerAdapter(getActivity().getSupportFragmentManager(),Titles,Numboftabs); // Assigning ViewPager View and setting the adapter pager = (ViewPager) rootView.findViewById(R.id.pager); pager.setAdapter(adapter); // Assiging the Sliding Tab Layout View tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs); tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width // Setting Custom Color for the Scroll bar indicator of the Tab View tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.tabsScrollColor); } }); // Setting the ViewPager For the SlidingTabsLayout tabs.setViewPager(pager); pager.setOffscreenPageLimit(3); pager.setOnPageChangeListener(new OnPageChangeListener() { public void onPageScrollStateChanged(int state) {} public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} public void onPageSelected(int position) { if(position ==0) { SwipeViewPagerAdapter.Pagename = "ListOnGoing"; } else if(position ==1) { SwipeViewPagerAdapter.Pagename = "ListUpComing"; } else if(position ==2) { SwipeViewPagerAdapter.Pagename = "ListExpired"; } } }); } catch(Exception e) { e.printStackTrace(); } return rootView; } } 

这是我的适配器:

 import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; /** * Created by Edwin on 15/02/2015. */ public class SwipeViewPagerAdapter extends FragmentPagerAdapter { CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created public static String Pagename="ListOnGoing"; // Build a Constructor and assign the passed Values to appropriate values in the class public SwipeViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) { super(fm); this.Titles = mTitles; this.NumbOfTabs = mNumbOfTabsumb; } //This method return the fragment for the every position in the View Pager @Override public Fragment getItem(int position) { switch (position) { case 0: //Pagename = "ListOnGoing"; ListOnGoing mListOnGoing = new ListOnGoing(); return mListOnGoing; case 1: //Pagename = "ListUpComing"; ListUpComing mListUpComing = new ListUpComing(); return mListUpComing; case 2: //Pagename = "ListExpired"; ListExpaire mListExpaire = new ListExpaire(); return mListExpaire; default: return null; } } // This method return the titles for the Tabs in the Tab Strip @Override public CharSequence getPageTitle(int position) { return Titles[position]; } // This method return the Number of tabs for the tabs Strip @Override public int getCount() { return NumbOfTabs; } } 

这是我的一个片段:

 import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @SuppressLint("ShowToast") public class ListOnGoing extends Fragment implements OnItemClickListener { Boolean isInternetPresent = false; ConnectionDetector connectdetector; public static ListView swipelisview; Activity activity; public static ProductListAdapter productListAdapter; SharedPreference sharedPreference; String LoggedIn; boolean fragmentAlreadyLoaded = false; @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); this.listener = (FragmentActivity) activity; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { try { super.onViewCreated(view, savedInstanceState); swipelisview = (ListView) rootView.findViewById(R.id.list); View emptyView = rootView.findViewById(R.id.emptyView); swipelisview.setEmptyView(emptyView); if (savedInstanceState == null && !fragmentAlreadyLoaded) { fragmentAlreadyLoaded = true; repoObject = SplashScreen.getRepo(); session = new SessionManager(getActivity()); HashMap<String, String> Radious = session.getRadiousName(); Radiosname = Radious.get(SessionManager.KEY_RadiousName); //LoadActivity.Status=""; GPlaces = new GetAllGooglePlaces(); GPlaces.GetOpportunityList("", Radiosname, getActivity()); DisPlayOppList(); } productListAdapter = new ProductListAdapter(getActivity(), GetAllGooglePlaces.ArrayListOngoing); swipelisview.setAdapter(productListAdapter); productListAdapter.notifyDataSetChanged(); session = new SessionManager(getActivity()); HashMap<String, String> Radious = session.getRadiousName(); Radiosname = Radious.get(SessionManager.KEY_RadiousName); searchedit = (EditText) rootView.findViewById(R.id.searchbox); Button searchbtn = (Button) rootView.findViewById(R.id.searchbtn); searchedit = (EditText) rootView.findViewById(R.id.searchbox); clearbtn = (Button) rootView.findViewById(R.id.clearbtn); searchedit.addTextChangedListener(watch); clearbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { LoadActivity.Status=""; searchedit.setText(""); GPlaces.GetOpportunityList("", Radiosname, getActivity()); DisPlayOppList(); } }); searchbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { getActivity().runOnUiThread(new Runnable() { public void run() { multipleCat = ""; GetAllGooglePlaces.ArrayListOngoing = new CopyOnWriteArrayList<>(); SearchText = searchedit.getText() .toString(); LoadActivity.Status = "Search"; if (LoadActivity.isOnline) { GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity()); DisPlayOppList(); } else { List<OpportunityTable> alloffers = repoObject.roffertable .getAlloffersbySearchKeyword(SearchText); if (alloffers != null) { GPlaces.FillArrayListOffline(alloffers,"OnGoing"); } } } }); } }); HashMap<String, String> user = session.getLogin(); LoggedIn = user.get(SessionManager.KEY_Login); if (LoggedIn == null) { LoggedIn = ""; } connectdetector = new ConnectionDetector(getActivity()); try { // Check if Internet present isInternetPresent = connectdetector.isConnectingToInternet(); } catch (Exception e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); } footerlayout = (LinearLayout) rootView.findViewById(R.id.footerlayout); footerlayout.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { swipelisview.requestDisallowInterceptTouchEvent(true); return true; } }); swipelisview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View v, final int position, long id) { InputMethodManager imm = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0); try { final DetailsViewpagerFragment mDetailsViewpagerFragment = new DetailsViewpagerFragment(); String url; if (LoadActivity.isOnline) { progresdialog = new ProgressDialog(getActivity()); progresdialog.setMessage(Html .fromHtml("<b>Search</b><br/>Loading Details...")); progresdialog.setIndeterminate(false); progresdialog.setCancelable(false); progresdialog.show(); ListDetails product = GetAllGooglePlaces.ArrayListOngoing .get(position); OpportunityID = product.getOfferID(); url = LoadActivity.BaseUri + "SaveUserViewedOpportunities"; JsonObjectRequest jsObjRequest; jsObjRequest = new JsonObjectRequest( Request.Method.POST, url, getSaveViewUserParams(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { pagename = "Userplaceslist"; mDetailsViewpagerFragment .setClickList(position); FragmentManager fragment = getFragmentManager(); fragment.beginTransaction() .replace(R.id.frame_container, mDetailsViewpagerFragment) .commit(); LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity; ModuleFragmentBackStackingClass .AddtoStack( mDetailsViewpagerFragment, EnumModuleTags.SinglePlaceActivity, getString(R.string.mainfrgment_rprt)); LoadActivity.updateActionbarMenu(); progresdialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse( VolleyError error) { Toast.makeText(getActivity(), "False", Toast.LENGTH_LONG).show(); progresdialog.dismiss(); } }); AppController.getInstance().addToRequestQueue( jsObjRequest); } else { mDetailsViewpagerFragment.setClickList(position); FragmentManager fragment = getFragmentManager(); fragment.beginTransaction() .replace(R.id.frame_container, mDetailsViewpagerFragment).commit(); LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity; ModuleFragmentBackStackingClass.AddtoStack( mDetailsViewpagerFragment, EnumModuleTags.SinglePlaceActivity, getString(R.string.mainfrgment_rprt)); } } catch (Exception e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); } } private JSONObject getSaveViewUserParams() { JSONObject params = new JSONObject(); HashMap<String, String> UserId = session.getUserID(); String UserIdVal = UserId.get(SessionManager.KEY_UserID); if (!(UserIdVal == null)) { UserIdVal = UserId.get(SessionManager.KEY_UserID); } else { UserIdVal = "0"; } try { params.put("UserId", UserIdVal); params.put("OpportunityID", OpportunityID); params.put("UserViewedID", 0); params.put("Shortlisted", true); params.put("KeyValue", null); } catch (JSONException e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); } return params; } }); // Click The FavoritesItem on LongPress swipelisview.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { InputMethodManager imm; imm = (InputMethodManager) getActivity() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0); try { ImageView button; button = (ImageView) view .findViewById(R.id.fav_checkbox); String tag = button.getTag().toString(); if (tag.equals(getString(R.string.grey_favcolor))) { sharedPreference.addFavorite(activity, GetAllGooglePlaces.ArrayListOngoing.get(position)); button.setTag(getString(R.string.red_favcolor)); button.setImageResource(R.drawable.checked); } else if (tag.equals(getString(R.string.red_favcolor))){ sharedPreference.removeFavorite(activity, GetAllGooglePlaces.ArrayListOngoing.get(position)); button.setTag(getString(R.string.grey_favcolor)); button.setImageResource(R.drawable.unchecked); } return true; } catch (NotFoundException e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } return true; } }); // Code placed here will be executed even when the fragment comes from // backstack } catch (Exception e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); } } // String APIkey ="AIzaSyCAekTB0o1MuSYvUb-8HTZxhlJHE8yBUfI"; @Override public void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); activity = getActivity(); sharedPreference = new SharedPreference(); //setRetainInstance(true); } catch (Exception e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); } } @SuppressWarnings("static-access") @SuppressLint({ "CutPasteId", "ClickableViewAccessibility" }) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { //setRetainInstance(true); try { Tracker t = ((Analytics) getActivity().getApplication()).getTracker( TrackerName.APP_TRACKER); t.setScreenName("UserPlaces Listview"); t.send(new HitBuilders.AppViewBuilder().build()); } catch(Exception e) { Toast.makeText(getActivity().getApplication(), "Error"+e.getMessage(), 1).show(); } rootView = inflater.inflate(R.layout.user_places_listview, container, false); swipelisview = (ListView) rootView.findViewById(R.id.list); View emptyView = rootView.findViewById(R.id.emptyView); swipelisview.setEmptyView(emptyView); return rootView; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return rootView; } TextWatcher watch = new TextWatcher(){ @Override public void afterTextChanged(Editable arg0) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence s, int a, int b, int c) { if(c == 0){ clearbtn.setVisibility(View.GONE); } else { clearbtn.setVisibility(View.VISIBLE); } }}; protected void LoadSearchPlaces(String searchparam) { try { if (LoadActivity.isOnline) { JsonArrayRequest movieReq = new JsonArrayRequest("http://192.168.2.10/RPRT.WebApi/api/RPRT/" + "SearchPlaces/"+searchparam, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { List<HashMap<String, String>> aList = new ArrayList<>(); for (int i = 0; i < response.length(); i++) { JSONObject json_data; try { json_data = response.getJSONObject(i); HashMap<String, String> hm = new HashMap<>(); hm.put("Address", json_data.getString("Address")); hm.put("City", json_data.getString("City")); hm.put("Latitude", json_data.getString("Latitude")); hm.put("Longitude", json_data.getString("Longitude")); aList.add(hm); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String[] from = { "Address"} ; int[] to = { R.id.tv }; SimpleAdapter adapterId = new SimpleAdapter(getActivity(), aList, R.layout.user_places_dropdown_listitem, from, to); //final AutoCompleteTextView autoCompView = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView); autoCompView.setAdapter(adapterId); autoCompView.setThreshold(1); // Pname.setThreshold(1); autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @SuppressWarnings("unchecked") @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { HashMap<String, String> hm = (HashMap<String, String>) parent .getAdapter().getItem(position); autoCompView.setText(hm.get("Address")); SplashScreen.nwLocation.setLatitude(Double.parseDouble(hm.get("Latitude"))); SplashScreen.nwLocation.setLongitude(Double.parseDouble(hm.get("Longitude"))); HashMap<String, String> Radious = session.getRadiousName(); final String Radiosname; Radiosname = Radious.get(SessionManager.KEY_RadiousName); multipleCat=""; ProgressDialog progresdialog = new ProgressDialog(getActivity()); progresdialog.setMessage(Html .fromHtml("<b>Search</b><br/>Loading Details...")); progresdialog.setIndeterminate(false); progresdialog.setCancelable(false); //progresdialog.show(); LoadActivity.Status=""; GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity()); DisPlayOppList(); searchdialog.cancel(); } }); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse( VolleyError error) { } }); AppController.getInstance().addToRequestQueue(movieReq); } } catch (Exception e) { e.printStackTrace(); } } private void DisPlayOppList() { try { pdialog = new ProgressDialog(getActivity()); pdialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Details...")); pdialog.setIndeterminate(false); pdialog.setCancelable(false); if(LoadActivity.Status.equals("Slidemenulist")) { int CategoryId = 0; switch (CopyOfListOnGoing.multipleCat) { case "Books": CategoryId = 1; break; case "BeautyandFashion": CategoryId = 2; break; case "Electronic": CategoryId = 3; break; case "Food": CategoryId = 4; break; case "HomeService": CategoryId = 5; break; case "Jobs": CategoryId = 6; break; case "RealEstate": CategoryId = 7; break; case "Vehicles": CategoryId = 8; break; } List<OpportunityTable> alloffers = repoObject.roffertable .getAllCatOpp(CategoryId , Radiosname); if (alloffers != null) { GPlaces.FillArrayListOffline(alloffers,"OnGoing"); } } else { List<OpportunityTable> alloffers = repoObject.roffertable .getAlloffers(Integer.parseInt(Radiosname)); if (alloffers != null) { GPlaces.FillArrayListOffline(alloffers,"OnGoing"); } } } catch (Exception e) { e.printStackTrace(); PostLogcatErrors ple = new PostLogcatErrors(); ple.PostLogcatErorrs(e); } } public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0); multipleCat = ""; DisPlayOppList(); } /* @Override public void onResume() { Log.e("DEBUG", "onResume of Userplace ListView"); super.onResume(); }*/ @Override public void onPause() { Log.e("DEBUG", "OnPause of Userplace ListView"); super.onPause(); } } 

其余的片段看起来是一样的。 请帮帮我。

Solutions Collecting From Web of "ViewPager数据从下一个屏幕返回时丢失"

经过一些研究,我得到了解决我的问题,我只是调用getChildFragmentManager()而不是getactivity()。getSupportFragmentmanager()。这解决了我的问题。谢谢StackOverFlow

在你的适配器中,扩展FragmentStatePagerAdapter而不是FragmentPagerAdapter它将解决你的问题,如果你在一个片段中使用ViewPager,那么你需要使用getChildFragmentManager()而不是getActivity()。getSupportFragmentManager()。 让我知道如果你有任何问题。

希望这可以帮助你:)

 public float getPageWidth(int position) { if (position == 0 || position == 2) { return 0.8f; } return 1f; } 
 pager = (ViewPager) rootView.findViewById(R.id.pager); pager.setOffscreenPageLimit(2);// no of fragments