onPageListener Is Not Working - java

I need some help with setting up the position of the Fragments in order for it to work with the the onPageListener so I can set the visibility of certain views. As I am new, I am rather unsure on how to do this. Thank you for your time and effort.
MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
viewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//need some help here//
if(position == 1) {
drawerGrid.setVisibility(View.VISIBLE);
} else {
drawerGrid.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Fragments.java
public class Fragments extends FragmentPagerAdapter {
public Fragments(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //need some help here//
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}

try this:
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
drawerGrid.setVisibility(View.GONE);
break;
case 1:
drawerGrid.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
use it like:
ViewPager.addOnPageChangeListener(pageChangeListener);
// do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
viewpager.post(new Runnable()
{
#Override
public void run()
{
pageChangeListener .onPageSelected(viewPager.getCurrentItem());
}
});

Related

Prevent repeating of items when i back to fragment

In my application , I have ViewPager containing 3 fragments (Home , Profile and More)
Home Fragment contain RecyclerView
when i navigate from Home Fragment to Profile Fragment or More Fragment, it work like expected.
But when i navigate back to Home Fragment , items in RecyclerView duplicate...
And when i navigate again and back , it duplicate again
Here is my MainActivity.java Code:
public class MainActivity extends AppCompatActivity {
TabLayout mainTabLayout;
ViewPager mainViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainTabLayout = findViewById(R.id.main_tablayout);
mainViewPager = findViewById(R.id.main_viewpager);
mainTabLayout.setupWithViewPager(mainViewPager);
//to put mainTabLayout Icons...
MainTabLayoutIcons();
}
//to Change MainLayout Icons...
private void MainTabLayoutIcons() {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// add fragments to the adapter
adapter.addFragment(new Home());
adapter.addFragment(new MyActivity());
adapter.addFragment(new More());
mainViewPager.setOffscreenPageLimit(0);
mainViewPager.setAdapter(adapter);
// Select Home tab as default tab on startup
mainViewPager.setCurrentItem(0);
mainTabLayout.getTabAt(0).select();
// Set tabs Initial icons
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_black);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
/* tabSelectedListener to change the icon color once it is selected
// and change it back once another tab is selected */
mainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_black);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
}
if (tab.getPosition() == 1) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_outline);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_outline);
}
if (tab.getPosition() == 2) {
mainTabLayout.getTabAt(0).setIcon(R.drawable.home_outline);
mainTabLayout.getTabAt(1).setIcon(R.drawable.user_outline);
mainTabLayout.getTabAt(2).setIcon(R.drawable.more_black);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//no need for it
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//no need for it
}
});
}
}
and here is ViewPagerAdapter Code:
//Adapter for mainActivity ...
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
public ViewPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragment(Fragment fragment) {
fragmentList.add(fragment);
}
}
and here is first Fragment Home.java Code:
public class Home extends Fragment {
View v;
public SwipeRefreshLayout mSwipeRefreshLayout;
public RecyclerView mainRecyclerView;
private LinearLayoutManager linearLayoutManager;
public final List<MyActivityModel> mainPosts = new ArrayList<>();
private PostAdapter mAdapter;
public Home() {
/*Required Empty Constructor... */
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle bundle) {
v = layoutInflater.inflate(R.layout.fragment_home, container, false);
mSwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.mainSwipeRefresh);
mainRecyclerView = (RecyclerView) v.findViewById(R.id.MainRecyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity());
mainRecyclerView.setLayoutFrozen(true);
mainRecyclerView.setNestedScrollingEnabled(false);
mainRecyclerView.setLayoutManager(linearLayoutManager);
mAdapter = new PostAdapter(mainPosts);
mainRecyclerView.setAdapter(mAdapter);
Swipe();
LoadPosts();
return v;
}
/**
* -----------------TODO: to load posts in Home RecyclerView...----------------
*/
public void LoadPosts() {
Query database = FirebaseDatabase.getInstance().getReference().child("Posts");
database.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
if (snapshot.exists()) {
MyActivityModel post = snapshot.getValue(MyActivityModel.class);
mainPosts.add(0, post);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void Swipe() {
//to refresh page after swipe
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
mainPosts.clear();
LoadPosts();
mSwipeRefreshLayout.setRefreshing(false);
Toast.makeText(v.getContext(),"Refreshed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
mSwipeRefreshLayout.setRefreshing(false);
}
}
}, 500);
}
});
}
}
and this is an image showing item reeating
Anyone can help me how to prevent this duplication...
You may need to use FragmentPagerAdapter instead of FragmentStatePagerAdapter. Also, set mainRecyclerView.setLayoutFrozen(true); to false because, it will stop everything in recyclerView.
When you need to use FragmentPagerAdapter?
FragmentStatePagerAdapter is more useful when there are a large number
of pages, working more like a list view. When pages are not visible to
the user, their entire fragment may be destroyed, only keeping the
saved state of that fragment. This allows the pager to hold on to
much less memory associated with each visited page as compared to
FragmentPagerAdapter at the cost of potentially more overhead when
switching between pages.
Example of FragmentPagerAdapter:
class viewpager_class extends FragmentPagerAdapter {
int tabcount;
public viewpager_class(#NonNull FragmentManager fm, int tab_count) {
super(fm, tab_count);
this.tabcount = tab_count;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment1 fragment1 = new Fragment1 ();
return todayBAFragment;
case 1:
Fragment2 fragment2 = new Fragment2 ();
return todayReminderDue;
case 2:
Fragment3 fragment3 = new Fragment3 ();
return currentTransaction;
default:
return null;
}
}
#Override
public int getCount() {
return tabcount;
}
}
Also, set adapter into ViewPager wherever you want show viewPager:
//set adapter into viewpager
viewpager_class viewpagerClass = new viewpager_class(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewpagerClass);
viewPager.setOffscreenPageLimit(2);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

Change the title of the page along with the fragment Android

I think the problem is that:
{
..
#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) {
}
});
..
this.setTitle("Home");
}
and:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Home home = new Home();
return Home;
case 1:
Mail mail = new Mail();
return mail;
default:
return null;
}
}
I would now like to show in place of the page title, the new Fragment setTitle
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Home home = new Home();
this.setTitle("change");
return Home;
case 1:
Mail mail = new Mail();
this.setTitle("change");
return mail;
default:
return null;
}
I know that is not correct, but I do not know what the correct syntax is a whole day I'm trying to solve, but nothing.
I would just change the title.
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Menu1");
arrayList.add("Menu2");
arrayList.add("Menu3");
arrayList.add("Menu4");
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
getSupportActionBar().setTitle(arrayList.get(position));
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int pos) {
// TODO Auto-generated method stub
}
});

How to show progress when swiping between fragments?

I have an activity with pager adapter which contains some fragments. I've also created a progressBar (horizontal) on the top of the activity. I need that the bar would show the progress when I am swiping through the fragments. For example, it should be grey when I am in the first fragment then gradually grow when I swipe through the fragments and fully green when I am in the last fragment.
mainActivity.java
public class testActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_adapter);
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
PagerAdapter.java
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 arg0) {
return this.fragments.get(arg0);
}
#Override
public int getCount() {
return this.fragments.size();
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
}
Actually I've found a very simple answer. This is what I did:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int pos) {
//This is because progress is 0 at the start of the program
progress++;
ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setProgress(position++);
}
});
You need to add OnPageChangeListener to you ViewPager in your Activity like this
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int pos) {
// Update the progress bar according to pos
// Also note that you reach the end when pos == mPagerAdapter.getCount() - 1
// and that pos starts at 0 - this is the first fragment
}
});

How to implement condition on view change using ViewPager

In my program i am using Fragments with ViewPager, where each and every Fragment contains 3 checkboxes, and i want to put a condition if user has not checked any of the checkbox don't switch to other fragment when swipe.
I know what could be the condition, but i don't know where to put ?
This condition will work for me, but where to use don't know:
if(!cb1.isChecked() && !cb2.isChecked() && !cb3.isChecked())
{
Toast.makeText(getActivity(), "Choose any one !", Toast.LENGTH_SHORT).show();
return view;
}
MainActivity.java:-
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}
ViewPagerAdapter.java:-
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
// Tab Titles
private String tabtitles[] = new String[] {
"Fragment 1",
"Fragment 2"
};
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
FragmentTab1.java:-
public class FragmentTab1 extends Fragment {
View view;
CheckBox cb1, cb2, cb3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
view = inflater.inflate(R.layout.fragmenttab1, container, false);
cb1 = (CheckBox) view.findViewById(R.id.cb1);
cb2 = (CheckBox) view.findViewById(R.id.cb2);
cb3 = (CheckBox) view.findViewById(R.id.cb3);
// control status of body frame checkboxes
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
cb2.setChecked(false);
cb3.setChecked(false);
}
}
});
cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
cb1.setChecked(false);
cb3.setChecked(false);
}
}
});
cb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
cb1.setChecked(false);
cb2.setChecked(false);
}
}
});
/**
** if(!cb1.isChecked() && !cb2.isChecked() && !cb3.isChecked())
{
Toast.makeText(getActivity(), "Choose any one !", Toast.LENGTH_SHORT).show();
return view;
}
***/
return view;
}
}
better idea is to disable viewpager from swiping and then again allow it so create custom one and use the method setPagingEnabled(boolean enabled)
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
} }
and in your xml you need:
<mypackage.CustomViewPager
android:id="#+id/myViewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />
Reference:
(i believe in copyright :-))
How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

Viewpager setCurrentItem() doesn't update onPageSelected()

When I swipe between questions, it loads current page number correctly
BUT when I use next button, first click doesnt loads pagenumber ( I mean onPageSelected() doesnt work.) second and other clicks loads content but it loads 1 page previous.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
mPager = (ViewPager)findViewById(R.id.pager);
QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();
mPager.setAdapter(mAdapter);
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
tv.setText( mPager.getCurrentItem()+"");
}
};
mPager.setOnPageChangeListener(pageChangeListener);
Question.next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(getItem(+1));
}
}
private int getItem(int i) {
int a = mPager.getCurrentItem();
i += a;
return i;
}
});
Why not just doing this in your listener:
mPager.setCurrentItem(mPager.getCurrentItem() + 1);

Categories

Resources