How to access controls(views)in tabs from another one in android?

1.6k views Asked by At

i'm working on application in eclipse that have 5 tab and i have spent much time for that but now i have a big problem :

when one of tabs is activated the next tab and prev tab is loading too and onCreated() method is called but i don't need that i need just calling onCreated() method when switching to tabs

enter image description here

This is my project files

mainActivity.java

package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import ir.zinoo.mankan.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.content.SharedPreferences;


public class MainActivity extends FragmentActivity implements ActionBar.TabListener {


    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Initilization

        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());



        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

         //Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setTabListener(this));
        }
        actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#333333")));

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

                }
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {


    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

    }
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

tabPagerAdapter.java class

package info.androidhive.tabsswipe.adapter;

import info.androidhive.tabsswipe.BmiFragment;
import info.androidhive.tabsswipe.CaloriFragment;
import info.androidhive.tabsswipe.FatFragment;
import info.androidhive.tabsswipe.KamarFragment;
import info.androidhive.tabsswipe.OstokhanFragment;
import info.androidhive.tabsswipe.OtherFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
            // Top Rated fragment activity
            return new BmiFragment();
        case 1:
            // Games fragment activity
            return new CaloriFragment();
        case 2:
            // Movies fragment activity
            return new KamarFragment();
        case 3:
            // Movies fragment activity
            return new OstokhanFragment();
        case 4:
            // Movies fragment activity
            return new FatFragment();
        case 5:
            // Movies fragment activity
            return new OtherFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
         //get item count - equal to number of tabs
        return 6;
    }

}

Now My question is How to avoid calling on created method of other tabs when in switch to special tab?

1

There are 1 answers

7
Kushal On BEST ANSWER

From Android Documentation about FragmentPagerAdapter :

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter

FragmentStatePagerAdapter :

This version of the pager 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.

So, as you are using FragmentPagerAdapter, FrgmentManager will add all your fragment in memory while user is using app. Furthermore, when user switches to any page, FragmentManager loads previous and next page and it will call onCreate() of your tabs.

As you have now 6 tabs, may be you want to add more tabs, FragmentStatePagerAdapter is more suitable.

For checking exactly which fragment is visible to user, you can do something like this :

public class TabsPagerAdapter extends FragmentPagerAdapter {

/* declare fragment objects here globally */
BmiFragment mBmi = new BmiFragment();
CaloriFragment mCalori = new CaloriFragment();
KamarFragment mKamar = new KamarFragment();


public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}
@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        // Top Rated fragment activity

        mBmi.setUserVisibleHint(false);
        return mBmi;
    case 1:
        // Games fragment activity

        mCalori.setUserVisibleHint(false);
        return mCalori;
    case 2:
        // Movies fragment activity

        mKamar.setUserVisibleHint(false);
        return mKamar;
    /* like this for all case*/
    }

    return null;
}

}

Set onPageChangeListener to ViewPager from your Activity :

mPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // position tab is visible to user
                switch(position) {
                    case 0 :
                        mBmi.setUserVisibleHint(true);
                        break;
                    /* like this for all case */
                 }
            }
        });

Override setUserVisibleHint() method in all fragments :

public class <Your_Fragment> extends Fragment {
  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // do something, your fragment is visible
    } else {  
        // your fragment is loaded, but not visible to user currently
    }
  }
}