How to refresh fragment onTabReselected? - android

Here's my code.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(getContext, "test", Toast.LENGTH_SHORT).show();
// toast is not working.
}
});
return view;
I want to refresh the fragment because I used API and I need to re-fetched the data everytime the tab is selected.

if(viewPager.getCurrentItem() == 0) {
Fragment1 fragment1 = (Fragment1) adapter.instantiateItem(viewPager, 0);
if (fragment1 != null) {
fragment1.fragmentBecameVisible();
}
}else if(viewPager.getCurrentItem() == 1) {
Fragment2 fragment2 = (Fragment2) adapter.instantiateItem(viewPager, 1);
if (fragment2 != null) {
fragment2.fragmentBecameVisible();
}
}
viewPager.setCurrentItem(tab.getPosition());
Add this two interface
public interface Fragment1 {
void fragmentBecameVisible();
}
public interface Fragment2 {
void fragmentBecameVisible();
}
and then implement fragment from that interface and use methos in your fragament
#Override
public void fragmentBecameVisible() {
//do your task heree
}

have a look at this tutorial. If any issue you can ask there. http://blog.tamanneupane.com/fragment-refresh/

override this method and call the method here.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
// this will call when the fragment is visible to the user.
// call your API or fetch_data() here.
}
}

You can use pull to refresh method if your base APIs are 18+
You can refer here https://github.com/codepath/android_guides/wiki/Implementing-Pull-to-Refresh-Guide it shows how to refresh fragments using pull to refresh. Been using it quite in my app. Cheers.

You can update the onResume() of your fragment to somewhat mentioned below or set viewPager.setOffscreenPageLimit(0/1); //I think its 0 but u can try & look what works for you!
#Override
public void onResume() {
super.onResume();
if(somecondition) {
call code executing API functionality
}
}

Try this
Set given code after set viewpager in tablayout :
TabLayout.Tab tab = tabLayout.getTabAt(current_tab);
tab.select();

Related

Skip tab in tablayout

I need to skip particular tab. When user scroll from 1st to 2nd tab control should move to 3rd tab and vice versa.
I have override the OnTabSelectedListener for Tablayout and calling below function in tabselected method, but no result.
private class TabChangeListener implements TabLayout.OnTabSelectedListener {
#Override
public void onTabSelected(TabLayout.Tab tab) {
changeTab(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Method to change tab.
private void changeTab(int pos) {
if (pos == 1) {
if (previousPos == 2) {
TabLayout.Tab tab = mTabLayout.getTabAt(0);
tab.select();
} else if (previousPos == 0) {
TabLayout.Tab tab = mTabLayout.getTabAt(2);
tab.select();
}
} else
previousPos = pos;
}
The design i want to implement

How to know whether the page is selected from Swipe or Click of Tab of Viewpager

I have a ViewPager which Toolbar tabs.
I have to know how many times user clicked tabs and how many times user swiped and selected a page.
I am using ViewPager.OnPageChangeListener() for this purpose.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override public void onPageSelected(int position) {
// Here i am sending the GA event
}
#Override public void onPageScrollStateChanged(int state) {
}
});
OnPageSelected is called for both click and swipe of page.
How will I differentiate the page selected is from click of tabs or its from swipe of Viewpager ?
Here is my solution. I am basing on single variable.
public class MainActivity extends AppCompatActivity {
// remember last action
private Action lastAction = Action.RESET;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
mViewPager = findViewById(R.id.viewPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
// No-op
}
#Override
public void onPageSelected(int i) {
if (lastAction == Action.RESET) {
lastAction = Action.SWIPE;
Log.d(TAG, "onPageSelected: SWIPED");
} else {
lastAction = Action.RESET;
}
}
#Override
public void onPageScrollStateChanged(int i) {
// No-op
}
});
mTabLayout = findViewById(R.id.tabLayout);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (lastAction == Action.RESET) {
lastAction = Action.SELECT;
Log.d(TAG, "onPageSelected: SELECTED");
} else {
lastAction = Action.RESET;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// No-op
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// No-op
}
});
}
}
Limitation:
Content for viewPager must be loaded before adding listeners because this solutions is basing on ordered calls (onTabSelected, onPageSelected).
Preview:
In this example I will be checking if the user selected the page at index 1 by swiping or by tapping the tab:
Note: You can use tabLayout.getChildAt(0) to get the main sliding layout, and
((ViewGroup) tabLayout.getChildAt(0)).getChildAt(desiredPosition) //to get the tab at desired position
Using this, we add onClickListener to the desired tab and once clicked, its onClick() method will be called first followed by the onTabSelected() method of the TabSelectedListener of the TabLayout.
private Boolean tabClicked = false; //variable which determines after entering the onTabSelected() method, if onClick was called or not
((ViewGroup) tabLayout.getChildAt(0)).getChildAt(1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tabClicked = true;
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if(tab.getPosition()==1){
if(tabClicked){
//your tab was clicked, do work here
}
else{
//your tab was swiped, do some work here
}
tabClicked = false;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {}
#Override
public void onTabReselected(TabLayout.Tab tab) {}
});
The tabview you use, is a textview. So there will be onclicklistener for this textview. You could track the tab click on onClick() method of listener!
Try this
fun onTabClickedListener(callback: String.() -> Unit){
tabContainer?.let { tabContainer->
for (i in 0 until tabContainer.tabCount) {
val text = tabContainer.getTabAt(i)?.text.toString() ?: ""
(tabContainer.getChildAt(0) as ViewGroup).getChildAt(i).tag = text
(tabContainer.getChildAt(0) as ViewGroup).getChildAt(i).setOnClickListener {
callback(text)
}
}
}
}```

TabLayout tab selection

How should I select a tab in TabLayout programmatically?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
If you know the index of the tab you want to select, you can do it like so:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
This technique works even if you're using the TabLayout by itself without a ViewPager (which is atypical, and probably bad practice, but I've seen it done).
This is how I solved it:
void selectPage(int pageIndex){
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
Use this:
tabs.getTabAt(index).select();
Keep in mind that, if currentTabIndex and index are same then this sends your flow to onTabReselected and not onTabSelected.
Use this:
<android.support.design.widget.TabLayout
android:id="#+id/patienthomescreen_tabs"
android:layout_width="match_parent"
android:layout_height="72sp"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="#android:color/white"
app:tabSelectedTextColor="#color/green"/>
After in OnClickListener:
TabLayout tabLayout = (TabLayout) findViewById(R.id.patienthomescreen_tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
Keep in mind that, if currentTabIndex and index are same then this sends your flow to onTabReselected and not onTabSelected.
This is probably not the ultimate solution, and it requires that you use the TabLayout together with a ViewPager, but this is how I solved it:
void selectPage(int pageIndex)
{
viewPager.setCurrentItem(pageIndex);
tabLayout.setupWithViewPager(viewPager);
}
I tested how big the performance impact of using this code is by first looking at the CPU- and memory monitors in Android Studio while running the method, then comparing it to the load that was put on the CPU and memory when I navigated between the pages myself (using swipe gestures), and the difference isn't significantly big, so at least it's not a horrible solution...
Hope this helps someone!
Just set viewPager.setCurrentItem(index) and the associated TabLayout would select the respective tab.
With the TabLayout provided by the Material Components Library just use the selectTab method:
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.selectTab(tabLayout.getTabAt(index));
It requires version 1.1.0.
If you can't use tab.select() and you don't want to use a ViewPager, you can still programmatically select a tab. If you're using a custom view through TabLayout.Tab setCustomView(android.view.View view) it is simpler. Here's how to do it both ways.
// if you've set a custom view
void updateTabSelection(int position) {
// get the position of the currently selected tab and set selected to false
mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(false);
// set selected to true on the desired tab
mTabLayout.getTabAt(position).getCustomView().setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
If you aren't using a custom view then you can do it like this
// if you are not using a custom view
void updateTabSelection(int position) {
// get a reference to the tabs container view
LinearLayout ll = (LinearLayout) mTabLayout.getChildAt(0);
// get the child view at the position of the currently selected tab and set selected to false
ll.getChildAt(mTabLayout.getSelectedTabPosition()).setSelected(false);
// get the child view at the new selected position and set selected to true
ll.getChildAt(position).setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
Use a StateListDrawable to toggle between selected and unselected drawables or something similar to do what you want with colors and/or drawables.
A bit late but might be a useful solution.
I am using my TabLayout directly in my Fragment and trying to select a tab quite early in the Fragment's Lifecycle.
What worked for me was to wait until the TabLayout finished drawing its child views by using android.view.View#post method. i.e:
int myPosition = 0;
myFilterTabLayout.post(() -> { filterTabLayout.getTabAt(myPosition).select(); });
You can try solving it with this:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
TabLayout.Tab tab = tabLayout.getTabAt(pos);
if (tab != null) {
tab.select();
}
Newest simple solution worked for me:
binding.tablayout.selectTab(binding.tablayout.getTabAt(tabPosisiton))
or
with(binding.tablayout) {
selectTab(getTabAt(tabPosisiton))
}
and tabPosition start from 0
try this
new Handler().postDelayed(
new Runnable(){
#Override
public void run() {
if (i == 1){
tabLayout.getTabAt(0).select();
} else if (i == 2){
tabLayout.getTabAt(1).select();
}
}
}, 100);
Kotlin Users:
Handler(Looper.getMainLooper()).postDelayed(
{ tabLayout.getTabAt(position).select() }, 100
)
This will also scroll your tab layout in case if it needs to scroll.
you should use a viewPager to use viewPager.setCurrentItem()
viewPager.setCurrentItem(n);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
A combined solution from different answers is:
new Handler().postDelayed(() -> {
myViewPager.setCurrentItem(position, true);
myTabLayout.setScrollPosition(position, 0f, true);
},
100);
I am using TabLayout to switch fragments. It works for the most part, except whenever I tried to select a tab programmatically using tab.select(), my TabLayout.OnTabSelectedListener would trigger the onTabSelected(TabLayout.Tab tab), which would cause me much grief. I was looking for a way to do programmatic selection without triggering the listener.
So I adapted #kenodoggy 's answer to my use. I was further facing a problem where some of the internal objects would return null (because they weren't created yet, because I was answering onActivityResult() from my fragment, which occurs before onCreate() in the case the activity is singleTask or singleInstance) so I wrote up a detailed if/else sequence which would report the error and fall through without the NullPointerException that would otherwise trigger. I use Timber for logging, if you're not using that substitute with Log.e().
void updateSelectedTabTo(int position) {
if (tabLayout != null){
int selected = tabLayout.getSelectedTabPosition();
if (selected != -1){
TabLayout.Tab oldTab = tabLayout.getTabAt(0);
if (oldTab != null){
View view = oldTab.getCustomView();
if (view != null){
view.setSelected(false);
}
else {
Timber.e("oldTab customView is null");
}
}
else {
Timber.e("oldTab is null");
}
}
else {
Timber.e("selected is -1");
}
TabLayout.Tab newTab = tabLayout.getTabAt(position);
if (newTab != null){
View view = newTab.getCustomView();
if (view != null){
view.setSelected(false);
}
else {
Timber.e("newTab customView is null");
}
}
else {
Timber.e("newTab is null");
}
}
else {
Timber.e("tablayout is null");
}
}
Here, tabLayout is my memory variable bound to the TabLayout object in my XML. And I don't use the scrolling tab feature so I removed that as well.
If you are using TabLayout with viewPager then this helps you. You set the TabLayout with ViewPager in addOnpagelistener.
if you want to set the TabLayout position directly(not click on the Tab individual) try below code tabLayout.getTabAt(position_you_want_to_set).select()
/* will be invoked whenever the page changes or is incrementally scrolled*/
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabLayout.getTabAt(position).select();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
This won't work for app that has ViewPager2 Implemented, For that, you need to use
viewPager2.setCurrentItem(position);
inside onConfigureTab, onConfigureTab if found when we use TabLayoutMediator
i.e
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0 : tab.setIcon(getResources().getDrawable(R.drawable.camera));
break;
case 1 : tab.setText("CHAT");
viewPager2.setCurrentItem(position); // when app starts this will be the selected tab
break;
case 2 : tab.setText("STATUS");
break;
case 3 : tab.setText("CALL");
break;
}
}
}
);
tabLayoutMediator.attach();
add for your viewpager:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
array.clear();
switch (position) {
case 1:
//like a example
setViewPagerByIndex(0);
break;
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
//on handler to prevent crash outofmemory
private void setViewPagerByIndex(final int index){
Application.getInstance().getHandler().post(new Runnable() {
#Override
public void run() {
viewPager.setCurrentItem(index);
}
});
}
By default if you select a tab it will be highlighted. If you want to select Explicitly means use the given commented code under onTabSelected(TabLayout.Tab tab) with your specified tab index position. This code will explains about change fragment on tab selected position using viewpager.
public class GalleryFragment extends Fragment implements TabLayout.OnTabSelectedListener
{
private ViewPager viewPager;public ViewPagerAdapter adapter;private TabLayout tabLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PaymentCardFragment(), "PAYMENT CARDS");
adapter.addFragment(new LoyaltyCardFragment(), "LOYALTY CARDS");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//This will be called 2nd when you select a tab or swipe using viewpager
final int position = tab.getPosition();
Log.i("card", "Tablayout pos: " + position);
//TabLayout.Tab tabdata=tabLayout.getTabAt(position);
//tabdata.select();
tabLayout.post(new Runnable() {
#Override
public void run() {
if (position == 0) {
PaymentCardFragment paymentCardFragment = getPaymentCardFragment();
if (paymentCardFragment != null) {
VerticalViewpager vp = paymentCardFragment.mypager;
if(vp!=null)
{
//vp.setCurrentItem(position,true);
vp.setCurrentItem(vp.getAdapter().getCount()-1,true);
}
}
}
if (position == 1) {
LoyaltyCardFragment loyaltyCardFragment = getLoyaltyCardFragment();
if (loyaltyCardFragment != null) {
VerticalViewpager vp = loyaltyCardFragment.mypager;
if(vp!=null)
{
vp.setCurrentItem(position);
}
}
}
}
});
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//This will be called 1st when you select a tab or swipe using viewpager
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//This will be called only when you select the already selected tab(Ex: selecting 3rd tab again and again)
}
private PaymentCardFragment getLoyaltyCardFragment() {
Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
if(f instanceof PaymentCardFragment)
{
return (PaymentCardFragment) f;
}
return null;
}
private LoyaltyCardFragment getPaymentCardFragment() {
Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
if(f instanceof LoyaltyCardFragment)
{
return (LoyaltyCardFragment) f;
}
return null;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
public List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}
This can help too
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
tablayout.getTabAt(i).select();
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
You can set TabLayout position using following functions
public void setTab(){
tabLayout.setScrollPosition(YOUR_SCROLL_INDEX,0,true);
tabLayout.setSelected(true);
}
If it so happens that your default tab is the first one(0) and you happen to switch to a fragment, then you must manually replace the fragment for the first time. This is because the tab is selected before the listener gets registered.
private TabLayout mTabLayout;
...
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tablayout, container, false);
mTabLayout = view.findViewById(R.id.sliding_tabs);
mTabLayout.addOnTabSelectedListener(mOnTabSelectedListener);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.tabContent, MyFirstFragment.newInstance()).commit();
return view;
}
Alternatively, you can consider calling getTabAt(0).select() and overriding onTabReselected like so:
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Replace the corresponding tab fragment.
}
This would work because you are essentially replacing the fragment on every tab reselect.
If you have trouble understanding, this code can help you
private void MyTabLayout(){
TabLayout.Tab myTab = myTabLayout.newTab(); // create a new tab
myTabLayout.addTab(myTab); // add my new tab to myTabLayout
myTab.setText("new tab");
myTab.select(); // select the new tab
}
You can also add this to your code:
myTabLayout.setTabTextColors(getColor(R.color.colorNormalTab),getColor(R.color.colorSelectedTab));
Try this way.
tabLayout.setTabTextColors(getResources().getColor(R.color.colorHintTextLight),
getResources().getColor(R.color.colorPrimaryTextLight));
if u are using TabLayout without viewPager this helps
mTitles = getResources().getStringArray(R.array.tabItems);
mIcons = getResources().obtainTypedArray(R.array.tabIcons);
for (int i = 0; i < mTitles.length; i++) {
tabs.addTab(tabs.newTab().setText(mTitles[i]).setIcon(mIcons.getDrawable(i)));
if (i == 0) {
/*For setting selected position 0 at start*/
Objects.requireNonNull(Objects.requireNonNull(tabs.getTabAt(i)).getIcon()).setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
}
}
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Objects.requireNonNull(tab.getIcon()).setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
Objects.requireNonNull(tab.getIcon()).setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.white), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Kotlin fix
viewPager.currentItem = 0
tabs.setupWithViewPager(viewPager)
TabLayout jobTabs = v.findViewById(R.id.jobTabs);
ViewPager jobFrame = v.findViewById(R.id.jobPager);
jobFrame.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(jobTabs));
this will select tab as view pager swipe page
With Viewpager2, Kotlin none of the other answers helped, only this worked below. position is from fragment result listener in my case:
TabLayoutMediator(binding.tabLayout, binding.viewPager2) { _, _ ->
binding.viewPager2 = position
}.attach()

Updating the contents on tab changed in view pager

I am scracthing my head for past 1 day but unable to find the solution.
In mine application there are two tabs under the toolbar
First tab is USER-TAB
the second one is ADMIN-TAB
In both the tabs there are the listView. When a ListItem on the USER-TAB is clicked a dialog appears and user take some action.
Now after this when the ADMIN-TAB is Selected the Admin should get refreshed with new sets of data. But It's not. On selecting the ADMIN-TAB the onResume() method and everyting is getting called but it is not able to update the list.
I wont be able to write the Whole code, I am giving some snippet.
Basically I have taken the code from this link
https://github.com/codepath/android_guides/wiki/Sliding-Tabs-with-PagerSlidingTabStrip
In My Main Activity I have written the OpPageChangeListener.
public class MaterialTab extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.material_main_sample);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
// Give the PagerSlidingTabStrip the ViewPager
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
tabsStrip.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if(position == 0){
MileUserFragment userFragment = new MileUserFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(userFragment);
ft.attach(userFragment);
ft.commit();
} if(position == 1){
MileAdminFragment adminFragment = new MileAdminFragment();
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(adminFragment);
ft.attach(adminFragment);
ft.commit();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
OnPageSelected You can see I am detaching and reattaching the fragment.Everything is working fine. Both Fragments OnResume() are getting called but the List is not getting changed. I don't undrstand why
For additional assistance i am adding snippet one Fragment. Hope this will give some Idea where i might be going wrong
public class MileUserFragment extends Fragment {
#Override
public void onResume() {
super.onResume();
new GetAdminDbTask().execute();
if(!internetUtil.isConnectedToInternet(getActivity())){
mSwipeRefreshLayout.setRefreshing(false);
mSwipeRefreshLayout.setEnabled(false);
}
}
public class GetAdminDbTask extends AsyncTask<Admin, Void, String> {
#Override
protected String doInBackground(Admin... parmas) {
_adminList = shipmentDbHandler.getAllAdmin();
return "";
}
#Override
protected void onPostExecute(String str) {
mAdminAdapter = new AdminAdapter(getActivity(), _adminList);
adminListView.setAdapter(mAdminAdapter);
mAdminAdapter.notifyDataSetChanged();
// Set the refresh Listener to false after the list has been loaded with new set of data
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}
if(_adminList.size() > 0 ){
mAdminAdapter = new AdminAdapter(getActivity(), _adminList);
adminListView.setAdapter(mAdminAdapter);
mAdminAdapter.notifyDataSetChanged();
}
}
}
}
public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Tab1", "Tab2" };
private FragmentManager fragmentManager;
public SampleFragmentPagerAdapter(FragmentManager fm) {
super(fm);
this.fragmentManager = fm;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
FragmentTransaction ft = null;
if(position == 0){
MileUserFragment userFragment = new MileUserFragment();
return userFragment;
}
if(position == 1){
MileAdminFragment adminFragment = new MileAdminFragment();
return archiveFragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Haah.. Finally i got an answer to after an heck of losing almost 1 and half days. It might be not completely good answer but atleast it is one of the closest I got.
First of all MainActivity.java looks like:
tabs.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
int scrollPosition = 0;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position == 0){
scrollPosition = 0;
}
if(position == 1){
scrollPosition = 1;
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == pager.SCROLL_STATE_IDLE){
if(scrollPosition == 0 && application.isActiveAction()){
viewPagerAdapter.notifyDataSetChanged();
application.setActiveAction(false);
}
if(scrollPosition == 1 && application.isArchiveAction()){
viewPagerAdapter.notifyDataSetChanged();
application.setArchiveAction(false);
}
}
}
});
Now what I have done here is I have set OnPageChangeListener and in this I am keeping track of the position whenever the tabs are changing. For my needs what i have done is i have created two boolean variables and setting it when any content on those tab are changing in Application scope. Now when the contents on one tab has been changed or some Action are done I am calling
viewPagerAdapter.notifyDataSetChanged() // Now this is the real gem
after invoking this it will make a call to the ViewPagerAdapter function
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE; // This will get invoke as soon as you call notifyDataSetChanged on viewPagerAdapter.
}
Also the Point is your ViewPagerAdapter should extend FragmentStatePageAdapter. Now the Point is
PagerAdapter.POSITION_NONE
will not cache the fragment and reload a new fragment for that tab position.
Basic idea is we should not make or retutn PagerAdapter.POSITION_NONE everytime on sliding of tab since it destroys the cached element and reload the fragment which affects UI performance.
So finally the basic thing is always check that whether on calling viewPagerAdapter.notifyDataSetChanged() the function getItemPosition() should also gets invoked. Hope it will help somebody. For better perfomance you can make changes according to your requirement.
I got the needed breakthrough and understanding from this post : #Louth Answer
Remove Fragment Page from ViewPager in Android
Just put
viewPager.setCurrentItem(tab.getPosition());
in your onTabSelected method like:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

last item removing error in ViewPager on TabFragment android

i have two custom button Add and Remove, And when i click on Add tab Work good, after when i remove tab its go ok, but when i remove last tab then i get following error.
java.lang.NullPointerException
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3699)
at android.view.ViewGroup.removeViewAt(ViewGroup.java:3663)
at app.burhanimumineenbrowser.HomeActivity$3.onClick(HomeActivity.java:184)
at android.view.View.performClick(View.java:4191)
at android.view.View$PerformClick.run(View.java:17229)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4963)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
When i remove first tab its del , second one also delete but after third tab i cant remove it, error say me null pointer.
Here is Add Button Code.
btNewtab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
COUNT_TAB+=1;
// viewPager.setAdapter(mAdapter);
actionBar.addTab(actionBar.newTab().setText("New Tabs")
.setTabListener(HomeActivity.this));
mAdapter.notifyDataSetChanged();
}
});
Remove button Code.
btCloseTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(COUNT_TAB>0) {
if(TAB_CURRENT>=0 && PAGE_CURRENT>=0) {
System.out.println("CLOSE PAGE AND TAB : "+TAB_CURRENT+" AND "+PAGE_CURRENT);
COUNT_TAB -=1;
// int ichektab=TAB_CURRENT-1;
int ip=viewPager.getCurrentItem();
viewPager.removeViewAt(ip);
actionBar.removeTabAt(TAB_CURRENT);
//actionBar.removeTab(iTab);
mAdapter.notifyDataSetChanged();
// viewPager.destroyDrawingCache();
/* if(ichektab>0){
// viewPager.setCurrentItem(ichektab);
viewPager.setCurrentItem(ichektab);
//actionBar.removeTabAt(TAB_CURRENT);
}*/
}
}
}
});
My Adapter
public class TabsPageAdapter extends FragmentStatePagerAdapter {
private long baseId = 0;
public TabsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new MyWebBrowser();
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
return COUNT_TAB;
}
}
} please kindly suggest me about this error. Thanks
Use this code in remove button:
before removing tab u making COUNT_TAB to reduce so it troughs NullPointerException
also in addtab button increment the count tab in last
btCloseTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(COUNT_TAB>0) {
if(TAB_CURRENT>=0 && PAGE_CURRENT>=0) {
System.out.println("CLOSE PAGE AND TAB : "+TAB_CURRENT+" AND "+PAGE_CURRENT);
// int ichektab=TAB_CURRENT-1;
int ip=viewPager.getCurrentItem();
viewPager.removeViewAt(ip);
actionBar.removeTabAt(TAB_CURRENT);
//actionBar.removeTab(iTab);
mAdapter.notifyDataSetChanged();
COUNT_TAB -=1;
// viewPager.destroyDrawingCache();
/* if(ichektab>0){
// viewPager.setCurrentItem(ichektab);
viewPager.setCurrentItem(ichektab);
//actionBar.removeTabAt(TAB_CURRENT);
}*/
}
}
}
});
View Pager page change listener
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int i, float v, int i2) {
NUM_TABS=i+1;
btTabCount.setText(""+NUM_TABS);
}
#Override
public void onPageSelected(int i) {
getActionBar().setSelectedNavigationItem(i);
PAGE_CURRENT=i;
System.out.println("CURRENT PAGE DISCRIPTION : "+PAGE_CURRENT);
mAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
Tab listener methods
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mAdapter.notifyDataSetChanged();
viewPager.setCurrentItem(tab.getPosition());
TAB_CURRENT=tab.getPosition();
iTab=tab;
System.out.println("CURRENT TAB DISCRIPTION : "+TAB_CURRENT);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
//viewPager.setCurrentItem(tab.getPosition());
}
Finally i solve error.
Th reason is viewpager pager screen limit. By default there viewpager have Two page limit, but i write first time i used this code
viewPager.setOffscreenPageLimit(COUNT_TAB);
And i solved it
viewPager.setOffscreenPageLimit(500);
and if use COUNT_TAB then add button code is
btNewtab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// COUNT_TAB+=1;
// viewPager.setAdapter(mAdapter);
actionBar.addTab(actionBar.newTab().setText("New Tabs")
.setTabListener(HomeActivity.this));
COUNT_TAB+=1;
mAdapter.notifyDataSetChanged();
viewPager.setOffscreenPageLimit(COUNT_TAB);
}
});
Put pager limit after notifydatasetchanged.
Hope you guys understand.

Categories

Resources