ViewPager + ListView animation lag - android

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 :(( )

Related

ViewPager and ImageGallery

The problem is this:
When you first choose a picture - everything is fine. If you swipe, and press the "back" button, after you open another image then will open last image which will opened.
The correct position is passed through the Bundle. I don’t understand where to look for the error.
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.image_fullscreen, container, false);
ImageView imageView = view.findViewById(R.id.image_fScreen);
Hit hit = hits.get(position);
Picasso.get().load(hit.getLargeImageURL())
.into(imageView);
container.addView(view);
return view;
}
#Override
public int getCount() {
return hits.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
DialogFragment:
public class FullScreenDialogFragment extends DialogFragment {
private ArrayList<Hit> hits;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private TextView author;
private TextView count;
private int selectedPosition;
private Button buttonShare;
private static FullScreenDialogFragment fullScreenDialogFragment;
private int rlyPosition;
public static FullScreenDialogFragment getInstance() {
if (fullScreenDialogFragment == null) {
fullScreenDialogFragment = new FullScreenDialogFragment();
}
return fullScreenDialogFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.DialogStyle);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_viewpager, container, false);
viewPager = view.findViewById(R.id.viewpager);
author = view.findViewById(R.id.author);
buttonShare = view.findViewById(R.id.btnShare);
count = view.findViewById(R.id.count);
hits = (ArrayList<Hit>) getArguments().getSerializable("hits");
selectedPosition = getArguments().getInt("position");
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(onViewPageChangeListener);
setItem(selectedPosition);
return view;
}
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
private void setItemInfo(int pos) {
count.setText((pos + 1) + " of " + hits.size());
Hit hit = hits.get(pos);
author.setText(hit.getUser());
}
ViewPager.OnPageChangeListener onViewPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
setItemInfo(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
I Guess the Problem is here
private void setItem(int pos) {
viewPager.setCurrentItem(pos, true);
setItemInfo(selectedPosition);
}
You might be passing the selectedPosition instead of currentPosition
Please check.
My problem was in creating DialogFramgent object.
I did it him in Singlton pattern and called it with old data.
Now in OnClick i'm created new object DialogFramget and him get new values.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fullScreenDialog = new FullScreenDialogFragment();
fullScreenDialog.setArguments(bundle);
fullScreenDialog.show(fragmentTransaction, "");

How to update fragments dynamically in viewpager android

I am working on one application which contains dynamic pages,so that i have taken viewpager.I created one fragment dynamically it creates,in that fragment i am calling webservice after success response i am refreshing data ,but fragment is not updating.I am using StatePagerAdapter.
code:
public class CustomPagerAdapter extends FragmentStatePagerAdapter
{
private ArrayList<InstituteVO> _instituteList;
private ArrayList<CourseItemVO> _courses;
public CustomPagerAdapter(FragmentManager fm, ArrayList<InstituteVO> instituteList)
{
super(fm);
_instituteList = instituteList;
_courses=new ArrayList<>();
}
#Override
public Fragment getItem(int position)
{
PagerItemFragment fragment = new PagerItemFragment();
fragment.setItemInfo(_instituteList.get(position), this);
// fragment.setCourses(_courses);
return fragment;
}
#Override
public int getCount()
{
return _instituteList.size();
}
public int getItemPosition(Object item) {
return super.getItemPosition(item);
}
public class PagerItemFragment extends BaseFragment implements OnWebServiceResponseListener,View.OnClickListener
{
private RecyclerView _courseView;
private CourseCustomRecycleAdapter _adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.institute_pager_layout, null);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setData();
}
private void setData()
{
callDataService(_item);
}
private void callDataService(String slug)
{
WebServiceController.getInstance().serviceGET(this, new InstituteProcessor(), url, AppConstants.METHOD_GET, slug);
}
#Override
public void onWebServiceResponseSuccess(OnWebServiceDataProcessListener response)
{
if (response != null && response instanceof InstituteProcessor)
{
_adapter.setData(((InstituteProcessor)response).getInstituteVO().getCourses());
}
}
}

Android: FragmentStatePageAdapter not updating ListView

I have android application.
Application minSDK:15
I have NavigationDrawer.
When click on first Navigation drawer menu item, my new fragment appears called MainFragment.
Everything is good, like in android tutorial.
Now in this fragment I need to implement simple ViewPager.
ViewPager will page Fragments.
Here is code:
public class MainFragent extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<Books> books;
BooksPageAdapter contentPageAdapter = new BooksPageAdapter(getFragmentManager(), books);
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.viewPager);
pager.setAdapter(contentPageAdapter);
}
private class BooksPageAdapter extends FragmentStatePagerAdapter {
private ArrayList<Books> books;
public BooksPageAdapter(FragmentManager fm, private ArrayList<Books> books) {
super(fm);
this.books = books;
}
#Override
public Fragment getItem(int pos) {
return BooksFragment.newInstance(books);
}
#Override
public int getCount() {
return 5;
}
} }
And BooksFragment:
public class BooksFragment extends Fragment {
private ArrayList<Books> books;
static ContentFragment newInstance(final ArrayList<Books> books) {
BooksFragment booksFragment = new BooksFragment();
Bundle args = new Bundle();
args.putSerializable("books", books);
contentFragment.setArguments(args);
return booksFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
books = (ArrayList<Books>) getArguments().getSerializable(“books”);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_books, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
updateUI(books);
}
public void updateUI(ArrayList<Books> books) {
ListView listView = (ListView)getActivity().findViewById(R.id.list_view);
listView.setAdapter(new MyArrayAdapter(getActivity(), books));
}
private class MyArrayAdapter extends ArrayAdapter<Books> {
public MyArrayAdapter(final Context context, final List<Books> list) {
super(context, R.layout.books_menu_item, R.id.title, list);
}
#Override
public View getView(final int position,
final View convertView,
final ViewGroup parent) {
final View row = super.getView(position, convertView, parent);
Book book = getItem(position);
textView.setText(book.getTitle());
return row;
}
}
}
The FirstPage looks awesome, like it should. I see list of books titles.
But on the second page, list view is empty. All other views on second page (like TextView..) are fine except ListView.
What I do wrong ?
P.S FragmentStatePageAdapter is from support13. Fragments are from android package, not from support4

Inflated layout from viewpager is null after created view

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

Two instances of the same ListFragment in one FragmentActivity using ViewPager

I have a FragmentActivity that uses a ViewPager to flip left and right through pages of data (two ListFragments).
public class StopsActivity extends FragmentActivity {
private ViewPager mViewPager;
private PagerTabStrip mPagerTabStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stops);
mPagerTabStrip =(PagerTabStrip)findViewById(R.id.pager_header);
mViewPager = (ViewPager)findViewById(R.id.pager);
mPagerTabStrip.setDrawFullUnderline(true);
mPagerTabStrip.setTabIndicatorColorResource(R.color.pagerTabStrip);
mViewPager.setAdapter(new StopsAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(0);
}
private class StopsAdapter extends FragmentPagerAdapter {
public StopsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return StopsFragment.newInstance(routename, Stop.FORWARD);
case 1:
return StopsFragment.newInstance(routename, Stop.BACKWARD);
}
return null;
}
#Override
public int getCount() { return 2;}
#Override
public CharSequence getPageTitle(int position) { /* implementation ... */}
}
}
Everything runs ok, but I think that the instantation of the second StopFragment invalidate the data of the first one when getItem is called.
public class StopsFragment extends ListFragment {
private StopsAdapter mStopsAdapter;
private ListView mListView;
private String routename;
private int direction;
public static StopsFragment newInstance(String routename, int direction) {
StopsFragment stopsFragment = new StopsFragment();
// Supply arguments
Bundle args = new Bundle();
args.putString("routename", routename);
args.putInt("direction", direction);
stopsFragment.setArguments(args);
return stopsFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the adapter
ArrayList<Stop> stops = ...
mStopsAdapter = new StopsAdapter(getActivity(), stops);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_stops, container, false);
// Attach the adapter
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mStopsAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The page "IDA" corresponds to StopFragment with argument Stop.FORWARD and the page "VUELTA" corresponds the StopFragment with argument Stop.BACKWARD. As you can see in the images below, just one of them (the last one instantiate) is populated:
What I'm doing wrong?
EDIT
This is StopsAdapter
class StopsAdapter extends BaseAdapter {
private ArrayList<Stop> stops;
private LayoutInflater inflater;
public StopsAdapter(Context context, ArrayList<Stop> stops) {
this.stops = stops;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stops.size();
}
#Override
public Object getItem(int position) {
return stops.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_stop, parent, false);
}
TextView name = (TextView)convertView.findViewById(R.id.tvStopName);
TextView description = (TextView)convertView.findViewById(R.id.tvStopDescription);
Stop stop = (Stop)getItem(position);
name.setText(stop.name);
if (stop.info != null) {
description.setText(stop.info);
}
return convertView;
}
}
Ok, my fault. The code that was giving me problems is the only that I haven't posted (ArrayList<Stop> stops = ...). The code about Fragments and ViewPager works correctly.

Categories

Resources