Inflated layout from viewpager is null after created view - android

When I add the viewpager fragment everything goes nice, but when I move to another apps and returns to my app, I have a weird problem that getView or inflated is null. It is showing the view, but I can't have access to it.
Here comes the Fragment that will be used in the ViewPager:
public class FragmentRestauranteBandejao extends Fragment {
JSONObject dados;
View inflated;
ExpandableListView cardapio;
List<String> refeicoes;
List<String> pratos_almoco;
List<String> pratos_janta;
Map<String, List<String>> bandejao = null;
ExpandableListAdapter adapter;
public static FragmentRestauranteBandejao newInstance(String restaurante){
FragmentRestauranteBandejao frag = new FragmentRestauranteBandejao();
Bundle args = new Bundle();
args.putString("restaurante", restaurante);
frag.setArguments(args);
return frag;
}
public void getDados(){
if(dados == null){
if(USPRestaurantes.getDados()){
dados = USPRestaurantes.getCardapioByRestaurante(getArguments().getString("restaurante"));
}else{
Log.d("debug", "Dados ainda não estão prontos");
return;
}
}
if(inflated == null){
Log.d("debug", "inflated eh null");
if(inflated == null){
return;
}
}
//... some code here that deals with the data that comes from a request made at USPRestaurantes.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflated = inflater.inflate(R.layout.fragment_cardapio, container, false);
return inflated;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
inflated = view;
prepararCardapio();
getDados();
}
public void prepararCardapio(){
cardapio = (ExpandableListView) getView().findViewById(R.id.cardapio);
cardapio.setClickable(true);
refeicoes = new ArrayList<String>(Arrays.asList("Almoço","Jantar"));
pratos_almoco = new ArrayList<String>();
pratos_janta = new ArrayList<String>();
pratos_almoco.add("");
pratos_janta.add("");
bandejao = new LinkedHashMap<String, List<String>>();
bandejao.put(refeicoes.get(0), pratos_almoco);
bandejao.put(refeicoes.get(1), pratos_janta);
adapter = new ExpandableListViewAdapter(getActivity(), refeicoes, bandejao);
cardapio.setAdapter(adapter);
}
ViewPager Fragment:
public class FragmentBandejoes extends Fragment{
private String[] tabs = {"Central", "Química", "Física"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ArrayList<Fragment> paginasBandeco;
public int dia_semana = 0;
ProgressDialog dialog;
private TabPageIndicator mIndicator;
int number = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
paginasBandeco = new ArrayList<Fragment>();
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("central"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("quimica"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("fisica"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflated = inflater.inflate(R.layout.fragment_bandejoes, container, false);
return inflated;
}
public void notifyFragments(){
for(int i=0; i<3; i++){
((FragmentRestauranteBandejao) mAdapter.getItem(i)).getDados();
}
if(dialog != null){
dialog.dismiss();
}
}
public void getCardapios(boolean update){
if(!USPRestaurantes.getDados() || update){
boolean request_made = USPRestaurantes.getCardapio(getActivity());
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
getCardapios(false);
viewPager = (ViewPager) getView().findViewById(R.id.pager_bandejoes);
mAdapter = new TabsPagerAdapter(((MainActivity) getActivity()).fragmentManager, paginasBandeco, tabs);
viewPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator) getActivity().findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mIndicator.setCurrentItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
And Finally the FragmentStatePagerAdapter:
public class FragmentBandejoes extends Fragment{
private String[] tabs = {"Central", "Química", "Física"};
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ArrayList<Fragment> paginasBandeco;
public int dia_semana = 0;
ProgressDialog dialog;
private TabPageIndicator mIndicator;
int number = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
paginasBandeco = new ArrayList<Fragment>();
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("central"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("quimica"));
paginasBandeco.add(FragmentRestauranteBandejao.newInstance("fisica"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflated = inflater.inflate(R.layout.fragment_bandejoes, container, false);
return inflated;
}
public void notifyFragments(){
for(int i=0; i<3; i++){
((FragmentRestauranteBandejao) mAdapter.getItem(i)).getDados();
}
if(dialog != null){
dialog.dismiss();
}
}
public void getCardapios(boolean update){
if(!USPRestaurantes.getDados() || update){
boolean request_made = USPRestaurantes.getCardapio(getActivity());
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
getCardapios(false);
viewPager = (ViewPager) getView().findViewById(R.id.pager_bandejoes);
mAdapter = new TabsPagerAdapter(((MainActivity) getActivity()).fragmentManager, paginasBandeco, tabs);
viewPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator) getActivity().findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);
mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mIndicator.setCurrentItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
Additional Info: When I swipe to the other tabs, the view gets recreated and then it shows the data.
Thanks in advance

From what I can tell reading you code is that you are not taking into consideration the fragment's lifecycle.
Fragments, as Activities, have Lifecycle methods that you should use in order for them to render correctly. I suggest using the onResume callback and with it check if you have any data to display. If you do display them in your fragment. If you don't do what you do when you create the fragmet

Related

viewPager.setCurrentItem() seems not working after saveOnIstanceState()

I have a fragment that implements a ViewPager, in this fragment, I save the ViewPager status using the onSaveInstanceState() method. I can save it in the bundle using viewPager.getCurrentItem(), but when I go to restore the status of the ViewPager, the viewPager.setCurrentItem() doesn't seem to work.
How can I save the fragment status correctly?
This is my fragment code
public class HomeFragment extends Fragment {
private ViewPager viewPager;
private ViewPagerAdapter adapter;
Integer[] colors=null;
List<Model> models;
private String[] mDescriptions;
private String[] mTitle;
private String mPlayerName;
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentItem", viewPager.getCurrentItem());
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
models = new ArrayList<>();
Resources res = getResources();
mDescriptions = res.getStringArray(R.array.newGameDescription);
mTitle = res.getStringArray(R.array.newGame);
models.add(new Model(R.drawable.ic_launcher_background,mTitle[0], mDescriptions[0]));
models.add(new Model(R.drawable.ic_launcher_background,mTitle[1], mDescriptions[1]));
models.add(new Model(R.drawable.ic_launcher_background,mTitle[2], mDescriptions[2]));
models.add(new Model(R.drawable.ic_launcher_background,mTitle[3], mDescriptions[3]));
adapter = new ViewPagerAdapter(getContext(), models, mPlayerName);
int orientation = getResources().getConfiguration().orientation;
adapter.setOrientation(orientation);
View view = inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) view.findViewById(R.id.gameModeViewPager);
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
return view;
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
viewPager.postDelayed(new Runnable() {
#Override
public void run() {
int item = savedInstanceState.getInt("currentItem");
viewPager.setCurrentItem(item);
}
}, 100);
}
}
}
Any suggestion and review are welcome, thanks in advance
onCreateView does not return bundle value from onSaveInstanceState you have to get it from onActivityCreated
#public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
viewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
int item = savedInstanceState.getInt("currentItem");
viewPager.setCurrentItem(item);
}
});
}

Same fragment with different contents in viewpager

I have one parent fragment where there is viewpager and tablayout.
Viewpager holds the fragment with different contents associated with it.
Every think works fine on swipe but whenever I tap on the different tabs of the tablayout, categoryId and categoryName of SwipableFragment is changed to adjacent tab's SwipableFragmet to the visible fragment.
Basically when I launch my FragmentAllNews (containing a ViewPager) it's shown the second fragment/page instead of the first and when I swipe to the second I see the third... In other words It's always shown the next or the previous fragment/page depending on the swipe direction (left or right).
Sorry For my bad english :(
here are my Fragments and FragmentStatePagerAdater class
###1 FragmentAllNews which holds the viewpager and tablayout
public class FragmentAllNews extends Fragment {
#Bind(R.id.tab_layout)
TabLayout tabLayout;
#Bind(R.id.all_news_viewpager)
ViewPager viewPager;
SessionManager sessionManager;
String categoryId;
String categoryName;
ArrayList<TabModel> tabs;
public static FragmentAllNews createNewInstance() {
FragmentAllNews fragmentAllNews = new FragmentAllNews();
return fragmentAllNews;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
tabs = sessionManager.getSwitchedNewsValue() == 0 ?
StaticStorage.getTabData(0) :
StaticStorage.getTabData(1);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_all_news, container, false);
ButterKnife.bind(this, fragmentView);
return fragmentView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setViewPager(tabs);
setTabLayout();
}
private void setTabLayout() {
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager(ArrayList<TabModel> tabs) {
ArrayList<NewsFragmentModel> frags = new ArrayList<>();
for (int i = 0; i < tabs.size(); i++) {
if (i == 0) {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(FragmentBreakingAndLatestNews.createNewInstance(categoryId, categoryName), categoryName));
} else {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(SwipableFragment.createNewInstance(categoryId, categoryName), categoryName));
}
}
NewsPagerAdapter adapter = new NewsPagerAdapter(getChildFragmentManager(),frags);
viewPager.setAdapter(adapter);
}
#Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
###2 SwipableFragment which the fragment attached to the viewpager
public class SwipableFragment extends Fragment implements NewsTitlesAdapter.RecyclerPositionListener {
#Bind(R.id.recycler_view)
RecyclerView recyclerView;
#Bind(R.id.progess)
ProgressBar progressBar;
#Bind(R.id.cat_id)
TextView categoryTextView;
ArrayList<NewsObj> newsObjs;
NewsTitlesAdapter newsTitlesAdapter;
SessionManager sessionManager;
private static String categoryId;
private static String categoryName;
public static SwipableFragment createNewInstance(String category_id, String category_name) {
SwipableFragment swipableFragment = new SwipableFragment();
Bundle box = new Bundle();
box.putString(StaticStorage.NEWS_CATEGORY_ID, category_id);
box.putString(StaticStorage.NEWS_CATEGORY, category_name);
swipableFragment.setArguments(box);
return swipableFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
categoryId = getArguments().getString(StaticStorage.NEWS_CATEGORY_ID);
categoryName = getArguments().getString(StaticStorage.NEWS_CATEGORY);
newsObjs = (sessionManager.getSwitchedNewsValue() == 0) ?
NewsData.getNewsRepublica(getActivity()) :
NewsData.getNewsNagarik(getActivity(),categoryName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipable, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("category", categoryId + " " + categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
newsTitlesAdapter = new NewsTitlesAdapter(newsObjs);
newsTitlesAdapter.setOnRecyclerPositionListener(this);
recyclerView.setAdapter(newsTitlesAdapter);
recyclerView.addOnScrollListener(new EndlessScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Log.i("categoryId", categoryId+" "+categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ArrayList<NewsObj> moreNews = sessionManager.getSwitchedNewsValue() == 0 ?
NewsData.getNewsRepublica(getContext()) :
NewsData.getNewsNagarik(getContext(),categoryName);
int curSize = newsTitlesAdapter.getItemCount();
newsObjs.addAll(moreNews);
newsTitlesAdapter.notifyItemRangeInserted(curSize, newsObjs.size() - 1);
progressBar.setVisibility(View.GONE);
}
}, 5000);
}
});
}
#Override
public void onChildItemPositionListen(int position, View view) {
if (view.getId() == R.id.news_share_text_view) {
} else if (view.getId() == R.id.news_show_detail_text_view) {
} else {
Intent newsDetailIntent = new Intent(getActivity(), NewsDetailActivity.class);
NewsObj newsObj = newsObjs.get(position);
newsObj.setNewsCategory(categoryName);
newsDetailIntent.putExtra(NewsDetailActivity.NEWS_TITLE_EXTRA_STRING, newsObj);
startActivity(newsDetailIntent);
}
}
}
###3 NewsPagerAdapter is the subclass extended from FragmentStatePagerAdapter
public class NewsPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<NewsFragmentModel> frags;
public NewsPagerAdapter(FragmentManager fm) {
super(fm);
}
public NewsPagerAdapter(FragmentManager fm,ArrayList<NewsFragmentModel> frags){
super(fm);
this.frags = frags;
}
#Override
public Fragment getItem(int position) {
return frags.get(position).getFrag();
}
#Override
public int getCount() {
return frags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return frags.get(position).getTitle();
}
}
###4 NewsFragmentModel
public class NewsFragmentModel {
private Fragment frag;
private String title;
public NewsFragmentModel(Fragment frag, String title) {
this.frag = frag;
this.title = title;
}
public Fragment getFrag() {
return frag;
}
public void setFrag(Fragment frag) {
this.frag = frag;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Am I doing any mistakes ? please help me.If you need more info please let me know. My final hope is Stackoverflow

how refresh view when change page?

i have a fragment activity that have 4 page and load from 4 link from internet
when program start customlist show lists but when i change page the view show white page
my fragment :
public class VpiAbsTestActivitynouser extends SherlockFragmentActivity {
private static final String[] CONTENT = new String[] {" page1","page2","page3","page4"};
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
TextView mSearchView;
public String[] xmlURLArray = new String[]{"link1.xml","link2.xml","link3.xml","link4.xml"};
protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
Intent i = new Intent(this, transparentone.class);
startActivity(i);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
mIndicator.setCurrentItem(1);
}
class TestFragmentAdapter extends FragmentPagerAdapter {
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putString("url", xmlURLArray[position]);
return customlist.newInstance(args);
}
#Override
public int getCount() {
return mCount;
}
public CharSequence getPageTitle(int position) {
return VpiAbsTestActivitynouser.CONTENT[position % VpiAbsTestActivitynouser.CONTENT.length].toUpperCase();
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
}
}
and my custom list code is :
public class customlist extends SherlockFragment {
int fragment_position_in_viewpager = 0;
// All static variables
public static customlist newInstance(Bundle args) {
customlist fragment = new customlist();
fragment.setArguments(args);
return fragment;
}
ListView list;
LazyAdapterbeth adapter1;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
URL = getArguments().getString("url");
}
new getFeed().execute();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(
R.layout.dovomi, container, false);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
fragment_position_in_viewpager = getArguments().getInt("position");
//Update the Fragment on ViewPager Position.
}
}
private class getFeed extends AsyncTask<Void, Void, Document> {
#Override
protected void onPreExecute() {
}
protected Document doInBackground(Void... params) {
}
protected void onPostExecute(Document doc) {
}
list=(ListView)getView().findViewById(R.id.list);
adapter1=new LazyAdapterbeth(getActivity(), songsList);
adapter1.notifyDataSetChanged();
list.setAdapter(adapter1);
how i can refresh view when change the view from page 1 to page 2 ?
As your code is very long, I didn't analyse it deeply but the following solutions come to my mind:
1) onCreateView for each fragment method is regularly called when fragment is recreated/its view hierarchy is recreated
Thus it can be one place for refreshing. However onCreateView is called slightly earlier than before paging displaying (usually where you display page nr 2, onCreateView for page number 3 is executed). The best idea is to put a short code displaying Toast in onCreateView and then you will know if it's ok for you.
2) Your main activity (extending FragmentActivity) can get 3 methods which are executed when swiping between fragments. It will look more or less in the following way:
public MyActivity extends FragmentActivity implements OnPageChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivityPageAdapter = new MainActivityPageAdapter (this, getSupportFragmentManager());
mainActivityViewPager = (ViewPager) findViewById(R.id.main_activity_view_pager);
mainActivityViewPager.setAdapter(mainActivityPageAdapter);
//set listener (for navigator)
mainActivityViewPager.setOnPageChangeListener(this);
}
//and now you have 3 methods
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
You can read more http://developer.android.com/reference/android/support/v4/view/ViewPager.OnPageChangeListener.html

ViewPager + ListView animation lag

I have a CarsFragment which is inculde cars. One page is one trade (Ferrari, Mercedes) and on every page has a list with models of actual trade.
The main view:
public class CarsFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cars_fragment, container, false);
pager = (ViewPager) view.findViewById(R.id.carsPager);
adapter = new CarsPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
return view;
}
}
Adapter:
public class CarsPagerAdapter extends FragmentStatePagerAdapter {
private final FragmentManager fm;
private String[] cars = new String[]{"Ferrari","Mercedes"};
public MatchesPageAdapter(final FragmentManager fm) {
super(fm);
this.fm = fm;
}
#Override
public int getCount() {
return cars.length;
}
#Override
public Fragment getItem(final int position) {
return FragmentModelList.newInstance(cars[position]);
}
#Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
super.destroyItem(container, position, object);
}
}
List:
public class FragmentModelList extends Fragment {
public static FragmentModelList newInstance(String trade) {
FragmentModelList fragmentModelList = new FragmentModelList();
Bundle args = new Bundle();
args.putString("trade", trade);
fragmentModelList.setArguments(args);
return fragmentModelList;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_matches_list_view, container, false);
list = (ListView) view.findViewById(R.id.modelList);
return view;
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
modelListAdapter = new ModelListAdapter(getActivity());
list.setAdapter(modelListAdapter);
loadModels();
}
private void loadModels() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(final Void... params) {
try {
List<Model> result = Downloader.getModelsByName(getArguments().getString("trade"));
modelListAdapter.setData(result);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (!success) {
// Show error
} else {
// Update list
modelListAdapter.notifyDataSetChanged();
}
}
}.execute();
}
}
and the modelListAdapter set row where one row inculde 2 image and some textview.
And the problem:
when i swiping on the viewpager it isn't smooth :( a loged it and when created the next or previous page (depends on swipe direction) the animation will be bad, is lagging.
What is the solution?
(SGS4 android 4.2.2 - where is the project butter :(( )

need help to fix code for getting current view in viewpager

Need help to fix a code I saw in a https://stackoverflow.com/a/9275732/1938357. The solution I need is get the current view onany page in my viewpager based application
Below is the code for reference
public View getCurrentView(ViewPager pager) {
for (int i = 0; i < pager.getChildCount(); i++) {
View child = pager.getChildAt(i);
if (child.getX() <= pager.getScrollX() + pager.getWidth()
&& child.getX() + child.getWidth() >= pager.getScrollX() + pager.getWidth()) {
return child;
}
}
return getChildAt(0);
I am trying to access the current view in the view pager and used the code above. It works fine when I scroll forwards. But when I scroll backwards then after 2 backward scrolls this stops working.
Public class myActivity extends FragmentActivity
//Variable declarations
protected void onCreate(Bundle savedInstanceState) {
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
View CurrView;
OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
doTextViewChnges();//access the text view and update it based on pageSelected
---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
}
mPager.setOnPageChangeListener(pageChangelistener);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
And below is my ScreenSlidePageFragment class
public class ScreenSlidePageFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "pagenumber";
public static final String ARG_PAGEARRAY = "pages";
private int mPageNumber;
//Declare other variables
#SuppressLint("NewApi")
public static ScreenSlidePageFragment create(int pageNumber, String[] pages, int bookmarkPageNumber, String storyName, int linesInOnePage) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
args.putStringArray(ARG_PAGEARRAY, pages);
fragment.setArguments(args);
return fragment;
}
#SuppressLint("NewApi")
public ScreenSlidePageFragment() {
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
pages = getArguments().getStringArray(ARG_PAGEARRAY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = (ViewGroup) inflater
.inflate(R.layout.activity_story, container, false);
//load layout with all components filled up for that page
loadView(rootView);
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
It is very hard to discuss in comments with example of code.
As I see in grepcode FragmentStatePagerAdapter.setPrimaryItem(), receive object as android.support.v4.app.Fragment. But you are receive ClassCastException when trying to cast object as Fragment. Can you check your casting: do you really cast object in android.support.v4.app.Fragment not in android.app.Fragment? If all right, add your exception message to your question, please.
UPDATE:
If your ScreenSlidePagerAdapter has method getCurrentView(), then your method 'getCurrentView()' can work like this:
public View getCurrentView(ViewPager pager) {
return ((ScreenSlidePagerAdapter) pager.getAdapter()).getCurrentView();
}
And method getCurrentView() of your ScreenSlidePagerAdapter:
public View getCurrentView() {
return currView;
}
UPDATE 2:
I've made some modification with your code:
Your Activity with private Adapter:
public class myActivity extends FragmentActivity implements ISelectItemListener {
// Your variable declarations and methods
#Override
protected void onCreate(Bundle savedInstanceState) {
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(
new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
final ScreenSlidePageFragment fragment = mPagerAdapter.getFragment(pageSelected);
if (fragment != null) {
fragment.doTextViewChnges();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
});
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
//Your variable declarations
private final ScreenSlidePageFragment[] mFragments;
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
mFragments = new ScreenSlidePageFragment[NUM_PAGES];
}
#Override
public int getCount() {
return NUM_PAGES;
}
// It will create new ScreenSlidePageFragment by position if it's not exsist
#Override
public android.support.v4.app.Fragment getItem(int position) {
if (getFragment(position) == null) {
mFragments[position] = ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
}
return getFragment(position);
}
// It will give you ScreenSlidePageFragment if it's exists, or null
public ScreenSlidePageFragment getFragment(int position) {
return mFragments[position];
}
}
}
Your Fragment:
public class ScreenSlidePageFragment extends Fragment {
//Your variables and methods
public static ScreenSlidePageFragment create(int pageNumber, String[] pages, int bookmarkPageNumber, String storyName, int linesInOnePage) {
final Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
args.putStringArray(ARG_PAGEARRAY, pages);
final ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
pages = getArguments().getStringArray(ARG_PAGEARRAY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = (ViewGroup) inflater.inflate(R.layout.activity_story, container, false);
loadView(rootView);
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
// Let's keep logic of modifications in fragment
public void doTextViewChnges() {
final View view = getView();
// do what you want with your View and his children
}
}

Categories

Resources