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.
Related
I am creating a Tab based application where the user can create tabs by clicking a button and can delete the tabs by clicking another button. I implemented this using Tab layout, Fragments and Viewpager.
I am able to get the current tab position when new tab is created by the function setuptablyout function. But when i clicked another tab ie moving to other tabs I am not able to toast the position.
I found that using tabLayout.addOnTabSelectedListener I can get the position, while that doesn't work here.
my Activity Code is:
public class MainActivity extends AppCompatActivity{
TextView textView;
private TabLayout tabLayout;
public static ViewPager viewPager;
public static ViewPagerAdapter adapter;
private ImageView add;
int selectedTabPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) findViewById(R.id.my_tab_layout);
add= (ImageView) findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this, viewPager, tabLayout);
viewPager.setAdapter(adapter);
createFirstFragment("POS "+adapter.getCount());
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"Pos onTabSelected: "+ tabLayout.getSelectedTabPosition(),Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(MainActivity.this, "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS "+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS "+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
Log.e("adapter.getCount()",String.valueOf(adapter.getCount()));
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void createFirstFragment(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
Log.e("adapter.getCount()",String.valueOf(adapter.getCount()));
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(MainActivity.this, "selectedTabPosition --> "+selectedTabPosition, Toast.LENGTH_SHORT).show();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
ViewPager class:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
PreferenceHelper prefs;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
mFragmentTags = new HashMap<Integer, String>();
prefs = new PreferenceHelper(context);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
Log.e("getCount()", String.valueOf(getCount()));
if (getCount() > 0)
tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
ImageView tabItemAvatar =
(ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(context, "selectedTabPosition --> "+selectedTabPosition, Toast.LENGTH_SHORT).show();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
prefs.remove("POS"+position);
}
}
/*#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
mFragmentTags.put(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
String tag = mFragmentTags.get(position);
if (tag != null) {
fragment = mFragmentManager.findFragmentByTag(tag);
}
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I am getting this weird behaviour that whenever I create new tabs the onTabSelected functions are calling multiple time that even when I create 3rd tab onTabslected toast shows Pos onTabSelected: 0,1 and not the just 2nd position which is supposed to be the 2nd position. What can I do to solve this?
My intention is to get some unique tab id so that I can identify each tab separately
you just create the newInstance constructor for creating fragment with arguments
in your FragmentChild
public static FragmentChild newInstance(int page, String title) {
FragmentChild fragmentChild = new FragmentChild ();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentChild.setArguments(args);
return fragmentChild;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
return view;
}
And then after in adapter class change this.
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
to
#Override
public Fragment getItem(int position) {
return FragmentChild.newInstance(position, "Page # 1");
}
I have not tested this code but, I think this code will help you to get your unique tab id..
test this code and let me know if it works
I am using view-pager with fragment in my application. i want to add and remove any key/value from hash-map but it gives me null pointer exception. there are 5 elements in hash-map if i remove last key from map then it works fine. How to solve it.
Below is my problem code :
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
public PagerAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager1);
final HashMap<String,Integer> sliderDataList = new HashMap<String,Integer>();
sliderDataList.put("0",R.drawable.first);
sliderDataList.put("1",R.drawable.second);
sliderDataList.put("2",R.drawable.three);
sliderDataList.put("3",R.drawable.four);
sliderDataList.put("4",R.drawable.xiaomi);
adapter1 = new PagerAdapter(getSupportFragmentManager(), sliderDataList, MainActivity.this);
viewPager.setAdapter(adapter1);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
remove("3");
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void remove(String s){
adapter1.remove(s);
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private HashMap<String, Integer> hMap;
private final Context context;
public PagerAdapter(FragmentManager fm, HashMap<String,Integer> hMap, Context context) {
super(fm);
this.hMap=hMap;
this.context=context;
}
#Override
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return new SliderFragment(hMap,context,position);
}
#Override
public int getCount() {
return hMap.size();
}
public void remove(String s){
hMap.remove(s);
adapter1.notifyDataSetChanged();
}
}
#SuppressLint("ValidFragment")
public static class SliderFragment extends Fragment {
private HashMap<String, Integer> urls;
private int imageResourceId;
ImageView imageView;
private Context ctx;
public SliderFragment(HashMap<String,Integer> urls, Context c, int pos) {
this.urls = urls;
this.imageResourceId = pos;
this.ctx = c;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_main, container, false);
imageView = (ImageView) view.findViewById(R.id.img);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(urls.get(imageResourceId +""));
return view;
}
}
}
public void remove(String s){
if(sliderDataList.containskey("3"))
{
containskey.remove("3");
adapter1.notifydataSetChanged();
}
}
Try this:
Iterator<Map.Entry<String,String>> iter = TestMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
if("Sample".equalsIgnoreCase(entry.getValue())){
iter.remove();
}
}
if you just want to remove the null pointer exception, then add this:
if (urls.get(imageResourceId + "") != null)
imageView.setImageResource(urls.get(imageResourceId + ""));
I want to get the TextView text of current page of ViewPager in toast in onPageSelected() . Remember my data is in array-list , if I remove any position from array-list that text should not be shown in toast on swipe view-pager.
Below is my code:
public class MainActivity extends FragmentActivity {
public static TextView tx;
CustomViewPager pager1;
List<Fragment> fragments1;
public PagerAdapter adapter1;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
#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);
adapter1.notifyDataSetChanged();
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
String S= (String) tx.getTag();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +S, Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentPagerAdapter {
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)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
return position;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < image.size(); i++) {
fList.add(MyImageSlider.newInstance(image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
String newid;
public static MyImageSlider newInstance(String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
tx = (TextView)view.findViewById(R.id.text);
tx.setText(newid);
tx.setTag(newid);
return view;
}
}
}
Please try this code
public class MainActivity extends FragmentActivity {
public static TextView tx;
CustomViewPager pager1;
List<Fragment> fragments1;
public PagerAdapter adapter1;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
#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);
adapter1.notifyDataSetChanged();
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(mCurrentPos);
String value = fragmntDta.getTextOnTextView();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +value, Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentPagerAdapter {
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)
{
if (object instanceof MyImageSlider ) {
return POSITION_NONE;
}
return POSITION_UNCHANGED;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
return position;
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < image.size(); i++) {
fList.add(MyImageSlider.newInstance(image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
String newid;
TextView textView;
public static MyImageSlider newInstance(String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextOnTextView(){
retrun textView.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
textView = (TextView)view.findViewById(R.id.text);
textView.setText(newid);
textView.setTag(newid);
return view;
}
}
public Fragment findFragmentByPosition(int position) {
MyImageSlider fragmentPagerAdapter = mAdapter;
return getSupportFragmentManager().findFragmentByTag("android:switcher:" + mHorizontalViewPager.getId() + ":" + fragmentPagerAdapter.getItemId(position));
}
}
you should follow AndiGeeky's solutions.
In addition to that solution, you can even get a view which is visible on that position.
View view = pager1.getChildAt(position);
and later on get that textview by using view.findViewById(R.id.textviewid)
your code should look something like this.
#Override
public void onPageSelected(int position) {
View view = pager1.getChildAt(position);
TextView tv = (TextView)view.findViewById(R.id.<textviewId>);
Toast toast = Toast.makeText(getApplicationContext(),"Text is " + tv.getText().toString(), Toast.LENGTH_SHORT);
toast.show();
}
Note : textviewId will be the id of your TextView which is in Fragment
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.
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;
}
}