im trying to create an image gallery.
i have a ViewPager that each Fragment contains an image (swipable image gallery is what im trying to accomplish).
i also have a GridView that onitemclick triggers the ViewPager in the selected position showing the clicked image.
my problem is that one swipe to right and one swipe to left shows the same image as the clicked one.
ive tried setoffscreenpagelimit with no success.
this is my viewpager activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
helper = new WeddHelper(this,"wedd.db",null,1);
pager = (ViewPager) findViewById(R.id.pager);
pager.setOnPageChangeListener(this);
Intent ing = getIntent();
curr = ing.getIntExtra("curr", 0);
byto = helper.getPhotos();
count = byto.size();
FragmentManager mg = getSupportFragmentManager();
fragments = new Vector<Fragment>();
for(int i = 0; i<count;i++){
fragments.add(Fragment.instantiate(this,GalleryFrag.class.getName()));
}
mAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments, this);
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(1);
pager.setCurrentItem(curr);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mCurrentPosition = position;
curr = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
public int getClicked(){
return curr;
}
public byte[] getPhotoToBeDisplayed(){
return byto.get(curr);
}
}
this is my custom adapter:
public class FragmentAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
private Context context;
public FragmentAdapter(FragmentManager fragmentManager,List<Fragment> fragments, Context context) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
this.context = context;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,object);
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
and this is the fragment:
public class GalleryFrag extends Fragment {
WeddHelper helper;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gallery_fragment, container, false);
ImageGallery myActivity = (ImageGallery) getActivity();
int curr = myActivity.getClicked();
byte[] photoToBeDisplayed = myActivity.getPhotoToBeDisplayed();
helper = new WeddHelper(getActivity(),"wedd.db", null, 1);
ArrayList<byte[]> imgs = helper.getPhotos();
Bitmap br = BitmapFactory.decodeByteArray(photoToBeDisplayed,0,photoToBeDisplayed.length);
Bitmap bi = BitmapFactory.decodeByteArray(imgs.get(curr),0,imgs.get(curr).length);
Toast.makeText(getActivity(), curr+"this is from frag", Toast.LENGTH_SHORT).show();
ImageView iv = (ImageView) v.findViewById(R.id.fragImage);
iv.setImageBitmap(br);
return v;
}
}
Related
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, "");
public class IMResponseActivity extendsAppCompatActivity implements
ViewPager.OnClickListener {
private static ViewPager viewPager_response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_imresponse);
setUI();
setViewPager();
} catch (Exception e) {
e.printStackTrace();
}
}
setViewPager() {
for (int i = 0; i < IMAGES.length; i++)
ImagesArray.add(IMAGES[i]);
viewPager_response = (ViewPager) findViewById(R.id.pager_response);
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
viewPager_response.setAdapter(new CommonSlideImageAdapter1(IMResponseActivity.this, ImagesArray));
}
public void onClick(View v) {
switch (v.getId()) {
/* case R.id.pager_response:
fragment = new ItemDetailFragment();
//Fragment fragment = new SingleProductFragment();
//Fragment fragment = new ProfileFragment();
// toolbar.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
imresponse_layout.setVisibility(View.INVISIBLE);
ft.add(R.id.container_response_details, fragment);
ft.addToBackStack(null);
ft.commit();
break;*/
}
}
// here is my Adapter Code
public class CommonSlideImageAdapter1 extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public CommonSlideImageAdapter1(Context context, ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, final int position) {
View imageLayout = inflater.inflate(R.layout.common_slideimage_layout1, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
imageView.setClickable(true);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
Their is no direct way to implement onItemClick listener and onClickListener in viewpager because it contains different fragments and fragments have their own listeners etc.
so the
first solution for this is implement click listener in fragment
Second solution is to implement your own click listener by extending viewpager class.
to do this there is great solution available
ViewPager OnItemClickListener
hope this will help you.
i have two viewpager i am removing current page of one viewpager from second pager. and add removed page again when swipe to next position. same process for second viewpager. Problem is add and remove method work fine if i use them in onCreate but not working in onPageSelected. and other problem is if i add any removed page on same position again it show me added page on current position of viewpager. i want page just add on that specific position but do not set on current position.
Below is my code.Any help will be appreciated.
public class MainActivity extends FragmentActivity {
CustomViewPager pager1,pager2;
List<Fragment> fragments1,fragments2;
public PagerAdapter adapter1;
public PagerAdapter1 adapter2;
int lostPositionRight;
int lostPositionLeft;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
ArrayList<String> imageNew = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
ArrayList<Integer> images = new ArrayList<Integer>() {{
add(R.drawable.first);
add(R.drawable.second);
add(R.drawable.three);
add(R.drawable.four);
add(R.drawable.xiaomi);
}};
ArrayList<Integer> imagesNew = new ArrayList<Integer>() {{
add(R.drawable.first);
add(R.drawable.second);
add(R.drawable.three);
add(R.drawable.four);
add(R.drawable.xiaomi);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
pager1 = (CustomViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new PagerAdapter(getSupportFragmentManager(), fragments1);
pager1.setAdapter(adapter1);
removeView1(1);
lostPositionLeft = 1;
adapter1.notifyDataSetChanged();
pager2 = (CustomViewPager) findViewById(R.id.pager2);
fragments2 = getFragments2();
adapter2 = new PagerAdapter1(getSupportFragmentManager(), fragments2);
pager2.setAdapter(adapter2);
pager2.setCurrentItem(1);
removeView2(0);
lostPositionRight = 0;
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
MyImageSlider fragmntDta = (MyImageSlider)findFragmentByPosition(pager1.getCurrentItem());
String value = fragmntDta.getTextOnTextView();
int p = Integer.parseInt(value);
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +p, Toast.LENGTH_SHORT);
toast.show();
addView2(lostPositionRight,lostPositionRight);
removeView2(p);
adapter2.notifyDataSetChanged();
lostPositionRight = p;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
pager2.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
MyImageSlider1 fragmntDta = (MyImageSlider1)findFragmentByPosition2(pager2.getCurrentItem());
String value1 = fragmntDta.getTextView();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +value1, Toast.LENGTH_SHORT);
toast.show();
int p = Integer.parseInt(value1);
addView1(lostPositionLeft,lostPositionLeft);
removeView1(p);
lostPositionLeft = p;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void addView1(int index,int position)
{
adapter1.addView1 (index,position);
adapter1.notifyDataSetChanged();
}
public void addView2(int index,int position)
{
adapter2.addView2 (index,position);
adapter2.notifyDataSetChanged();
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
public void removeView2 (int position)
{
adapter2.removeView2(pager2, position);
adapter2.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
notifyDataSetChanged();
return position;
}
public void addView1 (int index,int position)
{
fragments.add(index,MyImageSlider.newInstance(images.get(position),image.get(position)));
notifyDataSetChanged();
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<>();
for (int i = 0; i < images.size(); i++) {
fList.add(MyImageSlider.newInstance(images.get(i),image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
int imageid;
String newid;
TextView textView;
public static MyImageSlider newInstance(int id,String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putInt("imageid", id);
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextOnTextView(){
return (String) textView.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageid=getArguments().getInt("imageid");
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
ImageView iv=(ImageView)view.findViewById(R.id.image1);
textView = (TextView)view.findViewById(R.id.text);
iv.setImageResource(imageid);
textView.setText(newid);
return view;
}
}
public Fragment findFragmentByPosition(int position) {
PagerAdapter fragmentPagerAdapter = adapter1;
return getSupportFragmentManager().findFragmentByTag("android:switcher:" + pager1.getId() + ":" +
fragmentPagerAdapter.getItemId(position));
}
public class PagerAdapter1 extends FragmentStatePagerAdapter {
private List<Fragment> fragment;
public PagerAdapter1(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragment = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragment.get(position);
}
#Override
public int getCount() {
return this.fragment.size();
}
#Override
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
public int removeView2 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragment.remove (position);
pager.setAdapter (this);
notifyDataSetChanged();
return position;
}
public void addView2 (int index,int position)
{
fragment.add(index,MyImageSlider1.newInstance(imagesNew.get(position),imageNew.get(position)));
notifyDataSetChanged();
}
}
private List<Fragment> getFragments2() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < imagesNew.size(); i++) {
fList.add(MyImageSlider1.newInstance(imagesNew.get(i),imageNew.get(i)));
}
return fList;
}
public static class MyImageSlider1 extends Fragment {
int imageid;
String newid;
public TextView textView1;
public static MyImageSlider1 newInstance(int id,String s)
{
MyImageSlider1 slider=new MyImageSlider1();
Bundle b=new Bundle();
b.putInt("imageid", id);
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextView(){
return (String) textView1.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageid=getArguments().getInt("imageid");
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rightpager, container, false);
ImageView iv=(ImageView)view.findViewById(R.id.image2);
iv.setImageResource(imageid);
textView1 = (TextView)view.findViewById(R.id.text2);
textView1.setText(newid);
return view;
}
}
public Fragment findFragmentByPosition2(int position) {
PagerAdapter1 fragmentPagerAdapter2 = adapter2;
return getSupportFragmentManager().findFragmentByTag
("android:switcher:" + pager2.getId() + ":" + fragmentPagerAdapter2.getItemId(position));
}
}
First of all use FragmentStatePagerAdapter instead FragmentPagerAdapter.
But, for your desired purpose, you are going the wrong way.
Try doing this:
You said both view pagers are showing same thing. So there is no need too have two same list. One from each is enough.
ArrayList<String> imageNew = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
ArrayList<Integer> images = new ArrayList<Integer>() {{
add(R.drawable.first);
add(R.drawable.second);
add(R.drawable.three);
add(R.drawable.four);
add(R.drawable.xiaomi);
}};
Define an onPageChangedListener for your view pager. So every time the page changed, you have the index. Just make a clone from both your lists and remove the desired index and make a new adapter and set that for the other view pager.
I have a fragment(say X) which contain ViewPager and TabLayout and i am passing a fragment((say Y)with a list) three times to adapter of this viewpager but every time list is sorted by some parameter.
Y fragment contain RecyclerView. And i am passing that list to the adapter of this RecyclerView.
I am able to populate all the 3 tabs with fragment.But list inside recyclerview is not sorted.Only last tab with recyclerview was comming sorted
Please help me to find shortcoming of the code.
X Fragment
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_bus_fragment, null);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
List<Bus> departureTimeList = mBusList;
Collections.sort(departureTimeList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getDepartureTime().compareTo(rhs.getDepartureTime());
}
});
Fragment departureFragment = new AvailableRecyclerViewFragment(departureTimeList);
if (getArguments()!= null) {
departureFragment.setArguments(getArguments());
}
adapter.addFragment(departureFragment, "Departure");
List<Bus> durationTimeList = mBusList;
Collections.sort(durationTimeList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getDurationForSorting() - rhs.getDurationForSorting();
}
});
Fragment durationFragment = new AvailableRecyclerViewFragment(durationTimeList);
if (getArguments() != null) {
durationFragment.setArguments(getArguments());
}
adapter.addFragment(durationFragment, "Duration");
List<Bus> priceList = mBusList;
Collections.sort(priceList, new Comparator<Bus>() {
#Override
public int compare(Bus lhs, Bus rhs) {
return lhs.getFares() - rhs.getFares();
}
});
Fragment priceFragment = new AvailableRecyclerViewFragment(priceList);
if (getArguments()!= null) {
priceFragment.setArguments(getArguments());
}
adapter.addFragment(priceFragment, "Fare");
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
This is my adapter of viewpager.
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragments = new ArrayList();
private final List<String> mFragmentTitles = new ArrayList();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
Y fragment (AvailableRecyclerViewFragment.java)
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.available_list_fragment, null);
recycler_view = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new CustomRecyclerViewAdapter(getActivity(), mBusList);
adapter.notifyDataSetChanged();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setItemAnimator(new DefaultItemAnimator());
recycler_view.setHasFixedSize(true);
recycler_view.setAdapter(adapter);
return rootView;
}
Adapter for Recyclerview
public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.CustomViewHolder> {
private List<Bus> dataList;
Context mContext;
public CustomRecyclerViewAdapter(Context context, List<Bus> list) {
dataList = list;
mContext = context;
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView tv_departureTime;
public TextView tv_arrivalTime;
public TextView tv_duration;
public TextView tv_price;
public TextView tv_availableSeats;
public TextView tv_travels;
public TextView tv_busType;
public CustomViewHolder(View view) {
super(view);
tv_departureTime = (TextView) view.findViewById(R.id.tv_departureTime);
tv_arrivalTime = (TextView) view.findViewById(R.id.tv_arrivalTime);
tv_duration = (TextView) view.findViewById(R.id.tv_duration);
tv_price = (TextView) view.findViewById(R.id.tv_price);
tv_availableSeats = (TextView) view.findViewById(R.id.tv_availableSeats);
tv_travels = (TextView) view.findViewById(R.id.tv_travels);
tv_busType = (TextView) view.findViewById(R.id.tv_busType);
}
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_list_row, parent, false);
final Animation anim = AnimationUtils.loadAnimation(mContext, android.R.anim.slide_in_left);
itemView.setAnimation(anim);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
Bus bus = dataList.get(position);
holder.tv_arrivalTime.setText("" + bus.getArrivalTime());
String[] data = bus.getDuration().split(":");
holder.tv_departureTime.setText("" + bus.getDepartureTime());
holder.tv_duration.setText("" + data[0] + "hr " + data[1] + "min");
if (bus.getFareList() != null) {
String fare = "";
for (FareDetails tempFare : bus.getFareList()) {
fare = fare + tempFare.getTotalFare() + ("/");
}
holder.tv_price.setText("" + fare.substring(0, fare.length() - 1).toString());
} else {
holder.tv_price.setText("" + bus.getFares());
}
holder.tv_availableSeats.setText("" + bus.getAvailableSeats() + " seats");
holder.tv_travels.setText(bus.getTravels());
holder.tv_busType.setText(bus.getBusType());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
inside of Fragment X(where your ViewPager is) call method setOnPageChangeListener:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
As you see inside of onPageSelected() call notifyDataSetChanged for your viewpager adapter. Then it should sort fragment that you're on.
This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)
public class MainFragment extends Fragment{
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container, false);
adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Tab1Class tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
Tab2Class tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
Tab2Class:
public class Tab1Class extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tv1 = (TextView) rootView.findViewById(R.id.tv1);
writeText();
}
public void writeText(){
tv1.setText("TV1 text");
}
}
Tab1Class:
public class Tab2Class extends Fragment {
TextView tv2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
tv2 = (TextView) rootView.findViewById(R.id.tv2);
writeText();
}
public void writeText(){
tv2.setText("TV2 text");
}
}
.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
////////////////////////////Added////////////////////
public void callWrite(){
if(tab1 != null)
tab1.writeText();
if(tab2 != null)
tab2.writeText();
}
/////////////
.
.
.
Here's an alternative:
public class BlankFragment extends Fragment {
public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
public static final String EXTRA_STUFF = "this_is_stuff";
public static void notifyStuffHappening(Context context, String stuff){
Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
intent.putExtra(EXTRA_STUFF, stuff);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private StuffHappenedReceiver mStuffListener;
public static class StuffHappenedReceiver extends BroadcastReceiver {
final BlankFragment mFragment;
public StuffHappenedReceiver(BlankFragment fragment) {
this.mFragment = fragment;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {
mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
}
}
}
private void someStuffHappened(String stringExtra) {
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mStuffListener = new StuffHappenedReceiver(this);
}
#Override
public void onDetach() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
mStuffListener = null;
super.onDetach();
}
}
This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.
If the fragment is not attached, it won't be updated.
To update this fragment, call the static method "notifyStuffHappening"