I have a 7 tabs and their shared fragment whose data depends on XML received from url. The problem is if I set setOffscreenPageLimit(6) and for first tab, everything is fine for tab number 1 but tab number 2 to 7 shows the data from url that supposed to show in last tab.
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), this, negeri);
viewPager.setAdapter(mAdapter);
viewPager.setOffscreenPageLimit(6);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("List");
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
});
FragmentStatePagerAdapter;
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
static Context context;
static Resources res = null;
static String[] CONTENT = null;
public TabsPagerAdapter(FragmentManager fm, Context c, String negeri) {
super(fm);
context = c;
res = context.getResources();
CONTENT = res.getStringArray(R.array.values);
}
#Override
public ListFragment getItem(int index) {
return DaerahFragment.newInstance(CONTENT[index]);
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return CONTENT.length;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
ListFragment;
public static ListFragment newInstance(String daerahVal) {
// TODO Auto-generated method stub
Bundle args = new Bundle();
args.putString(ARG_DAERAH, daerahVal);
DaerahFragment fragment = new DaerahFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle args = getArguments();
//String daerah=args.getString("daerah");
daerah = getArguments().getString(ARG_DAERAH);
Toast.makeText(getActivity(), "daerah= " + daerah , Toast.LENGTH_SHORT).show();
URL = "http://www.url.com/android/daerahMarker.php?daerah="+daerah;
setRetainInstance(true);
if (mListViewScrollPos != null && adapter != null) {
getListView().onRestoreInstanceState(mListViewScrollPos);
} else {
myTask = new TalkToServer();
myTask.execute();
}
}
TQ
i solved this
just remove static
static String URL = "";
to
String URL = "";
:)
Related
when i run this code,the toast in two different fragments are displayed on one tab. when i swipe to next tab nothing is displayed.
this is is my main tab activity:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Offers", "Distance", "Happy Hours","Shop List" };
#SuppressLint("NewApi")
#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().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
}
this is adapter class :
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle = new Bundle();
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Fragment of = new OfferFragment();
bundle.putString("OfferFragment", "OfferFragment");
of.setArguments(bundle);
return of;
case 1:
Fragment df = new DistanceFragment();
bundle.putString("DistanceFragment", "DistanceFragment");
df.setArguments(bundle);
return df;
case 2:
Fragment hf = new HappyHoursFragment();
bundle.putString("HappyHoursFragment", "HappyHoursFragment");
hf.setArguments(bundle);
return hf;
case 3:
Fragment sf = new ShoplistFragment();
bundle.putString("ShoplistFragment", "ShoplistFragment");
sf.setArguments(bundle);
return sf;
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
this is my first fragment :
public class OfferFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// public static final String ARG_OBJECT = "object";
View rootView = inflater.inflate(R.layout.offerfragment, container,
false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.offer);
name = args.getString("OfferFragment");
txtview.setText(args.getString("OfferFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
this is my second fragment :
public class DistanceFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.distancefragment, container, false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.distance);
name = args.getString("DistanceFragment");
txtview.setText(args.getString("DistanceFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
any suggestions are appreciated. am stuck with this.
This is because next fragment is created by pager
before showing toast check if that fragment is visible or not
if(fragmentName.this.isVisible())
{
// do your stuff here
}
Write onResume() in every fragment class.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Display Toast message here
}
}
I have to call a fragment (Page1) from here...
protected void onPostExecute(Void args) {
Intent intentx;
intentx = new Intent(HomeFragment.this.getActivity(),Main.class);
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentx);
}
I my program i have Main class which looks like this
public class Main extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Express(1 Day)", "Premium (2 Day)", "Normal (3+ Days)" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab);
// 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().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
This class will invoke Page1,Page2,Page3
Inside Page 1 the code is this
public class Page1 extends Fragment {
public static ArrayList<String> strArr;
public static ArrayList<ArrayList<String>> content;
public static ArrayAdapter<String> adapter;
LinearLayout ll;
View format;
float days_to_del;
int[] no_of_count= new int[20];
int count;
int x;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.page1, container, false);
// super.onResume();
//View rootView = inflater.inflate(R.layout.page1, container, false);
for(int j=0;j<10;j++)
{
days_to_del=Float.parseFloat(""+Lib.result[j][0].toString());
if(days_to_del==2.0)
{
no_of_count[x]=j;
x++;
count++;
}
}
for(int m=0;m<count;m++)
{
ll = (LinearLayout) rootView.findViewById(R.id.parent);
LayoutInflater vi = (LayoutInflater) Page1.this.getActivity().getApplicationContext().getSystemService(Page1.this.getActivity().LAYOUT_INFLATER_SERVICE);
format = inflater.inflate(R.layout.page1, null);
ll.addView(format);
//Lib.ShowAlertMessage(Page1.this.getActivity().getApplicationContext(), "", ""+format.getId());
if(Lib.result[no_of_count[m]][2].toString().equals("First Flight Couriers"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/first_flight";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
else if(Lib.result[no_of_count[m]][2].toString().equals("SkyNet WorldWide Express"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/skynet";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
else if(Lib.result[no_of_count[m]][2].toString().equals("The Professional Couriers"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/professional";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
else if(Lib.result[no_of_count[m]][2].toString().equals("The Professional Couriers"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/professional";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
TextView textView2=(TextView)rootView.findViewById(R.id.textView2);
textView2.setText("Rupees");
}
if(format.getId()==1)
{
ll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intentx;
intentx = new Intent(Page1.this.getActivity(), From.class); //mContext is a Context variable.
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
if(format.getId()==2)
{
ll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intentx;
intentx = new Intent(Page1.this.getActivity(), To.class);
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
return rootView;
}
public void onResume(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
}
}
My Issue
1. I use these variables(Lib.results[][]) in the PostExecute They are available ( I dont require here)
2. In the fragment Page1 i am not able access the Lib.results[][] , as soon as it enters the Page1 the value of result[][] is null as the value is not updated(this is what I guessed would have hapened)
3. The results based on the values will go to respective fragments (Page1,Page2,Page3)
Question
Am i calling the fragment activity the rightway?? does intent work this way or is there any other method.
I figured that I had used the array as String but changing it to strArray made it work
it is a few days I try to solve this problem whitout success. Please help me.
I use the tabs navigation with viewpager.There are four fragments. I use async task for download the data I need to put in the view. when the app is started, the first fragments is ampty. But when i swipe to the second or the third, they have data. if i swipe from the second to the first, it has data too. so i guess i may be something wrong with notifyDataSetChanged, but i tried and it doesnt work.
MainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//private ArrayList hasLoadedPages = new ArrayList<Integer>();
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
//case 0:
// return new LaunchpadSectionFragment();
default:
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
String str="";
if (position==0){
str = "one";
}else if(position==1){
str = "two";
}else if(position==2){
str = "three";
}else if(position==3){
str = "four";
}
return str;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
mCid = args.getInt(ARG_SECTION_NUMBER);
mNewsData = new ArrayList<HashMap<String,Object>>();
mNewsList = (ListView)getView().findViewById(android.R.id.list);
mNewsListAdapter = new SimpleAdapter(this.getActivity(), mNewsData, R.layout.newslist_item,
new String[]{"newslist_item_title","newslist_item_digest","newslist_item_source","newslist_item_ptime"},
new int[]{R.id.newslist_item_title,R.id.newslist_item_digest,R.id.newslist_item_source,R.id.newslist_item_ptime});
View loadMoreLayout = this.getLayoutInflater(savedInstanceState).inflate(R.layout.loadmore, null);
mNewsList.setAdapter(mNewsListAdapter);
mNewsList.addFooterView(loadMoreLayout);
mNewsList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
startActivity(intent);
intent.putExtra("newsDate", mNewsData);
intent.putExtra("position", position);
startActivity(intent);
}
});
mLoadMoreBtn = (Button)getView().findViewById(R.id.loadmore_btn);
mLoadMoreBtn.setOnClickListener(loadMoreListener);
loadNewsAsyncTask = new LoadNewsAsyncTask();
loadNewsAsyncTask.execute(mCid,0,true);
}
}
private static class LoadNewsAsyncTask extends AsyncTask<Object, Integer, Integer>
{
#Override
protected void onPreExecute()
{
mLoadMoreBtn.setText(R.string.loadmore_txt);
}
#Override
protected Integer doInBackground(Object... params)
{
return getSpeCateNews((Integer)params[0],mNewsData,(Integer)params[1],(Boolean)params[2]);
}
#Override
protected void onPostExecute(Integer result)
{
switch (result)
{
case NONEWS:
mLoadMoreBtn.setText(R.string.no_news);
break;
case NOMORENEWS:
mLoadMoreBtn.setText(R.string.no_more_news);
break;
case LOADERROR:
mLoadMoreBtn.setText(R.string.load_news_failure);
break;
}
mNewsListAdapter.notifyDataSetChanged();
mLoadMoreBtn.setText(R.string.loadmore_btn);
}
}
You are using FragmentPagerAdapter please change it to FragmentStatePagerAdapter and run again
Difference between FragmentPagerAdapter and FragmentStatePagerAdapter
About FragmentPagerAdapter Google's guide says:
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.
And about 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.
I try to develop a system to make a relation between tabs and fragment. You will see bellow my code and the view.
The Fragment manage the swipe, and the tabs the navigation directly on the click.
I manage to modify the Selected Tab when the user Swipe, but I can't do the inverse. That the view changes when I click on a tab.
Do you understand my question and have you the solution please ?
This is my main activity :
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
TextView tw;
ActionBar myActionBar;
ArrayList<Category> ListOfCategory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myActionBar = getActionBar();
myActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ListOfCategory = new ArrayList<Category>();
try {
List<String> categList = new ExecuteJsonLinkTask().execute("http://www.76actu.fr/json.php?d=categories&a=list&key=8smA5YjLG1132zbz301tM94jZO30B7dW").get();
for (String item : categList) {
JSONArray jArray = new JSONArray(item);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Category categ = new Category();
categ.setCategIdSite(json_data.getInt("term_id"));
categ.setName(json_data.getString("name"));
categ.setMoreArticle(true);
categ.setArticleAvailable(false);
if(json_data.getInt("term_id") == 89871){
categ.setActive(false);
} else categ.setActive(true);
Tab tab = myActionBar.newTab();
tab.setText(json_data.getString("name"));
Object obj = new Object();
obj = String.valueOf(json_data.getInt("term_id"));
tab.setTag(obj);
tab.setTabListener(new MyTabListener(getBaseContext()));
// tab.setTabListener(new MyTabListener(getBaseContext()));
myActionBar.addTab(tab);
ListOfCategory.add(categ);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
myActionBar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
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;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Category> ListOfCategory = new ArrayList<Category>();
Fragment fragment;
ActionBar myActionBar;
public SectionsPagerAdapter(FragmentManager fm){
super(fm);
myActionBar = getActionBar();
try {
List<String> categList = new ExecuteJsonLinkTask().execute("[API_LINK]").get();
for (String item : categList) {
JSONArray jArray = new JSONArray(item);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Category categ = new Category();
categ.setCategIdSite(json_data.getInt("term_id"));
categ.setName(json_data.getString("name"));
categ.setMoreArticle(true);
categ.setArticleAvailable(false);
if(json_data.getInt("term_id") == 89871){
categ.setActive(false);
} else categ.setActive(true);
ListOfCategory.add(categ);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position);
args.putInt("categId", ListOfCategory.get(position).getCategIdSite());
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show total pages.
return ListOfCategory.size();
}
#Override
public CharSequence getPageTitle(int position) {
return ListOfCategory.get(position).getName();
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
TextView dummyTextView;
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
int position = getArguments().getInt(ARG_SECTION_NUMBER);
dummyTextView.setText(Integer.toString(getArguments().getInt("categId")));
return rootView;
}
}
public class MyTabListener implements TabListener{
public Context context;
MyTabListener(Context context) {
this.context = context;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// HERE
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
}
This is a screenshot of my application : http://i.stack.imgur.com/HBKUj.png
I do not think you need it but I can give you this.
Thanks a lot
http://i.stack.imgur.com/HBKUj.png
In my code i have this solution and it works:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
public static String TAG="MAIN_ACTIVITY";
public static Context mContext;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "FRIENDS", "CHAT", "MAP" };
//ON CREATE METHOD:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
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 onTabSelected(ActionBar.Tab tab, FragmentTransaction ft)
{
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft){}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {}
}
TabsPagerAdapter class:
public class TabsPagerAdapter extends FragmentPagerAdapter
{
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
//switch names of your fragments:
switch (index) {
case 0:
return new Stats_Fragment();
case 1:
return new FightsFragment();
case 2:
return new SearchFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
You must add this line in your Activity xml file, this is my case:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.MainActivity">
//ADD THIS AND PROBLEM WILL BE SOLVED:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</FrameLayout>
I have an ActionBar that contains 11 tabs and 1 fragment. I also have a ViewPager to display the fragment(s). When a tab is clicked it creates the same fragment. The tabs display dates so they change everyday. What I need is to send the text of the tab (ie. .getTabText()) to the fragment, this will change the content of the fragment. I am having so much trouble trying to figure out how to do this. Here is all my code:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private ArrayList<TopRatedFragment> myFragmentList = new ArrayList<TopRatedFragment>();
// Tab titles
String[] tabs = {this.getCurrentDate(-5).toString(),this.getCurrentDate(-4).toString(),this.getCurrentDate(-3).toString(), this.getCurrentDate(-2).toString(),this.getCurrentDate(-1).toString(),
this.getCurrentDate(0).toString(),
this.getCurrentDate(1).toString(), this.getCurrentDate(2).toString(), this.getCurrentDate(3).toString(), this.getCurrentDate(4).toString(), this.getCurrentDate(5).toString(),};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (String tab_name : tabs) {
TopRatedFragment fm = new TopRatedFragment();
fm.getTabs(tab_name);
myFragmentList.add(fm);
}
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), myFragmentList);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
actionBar.setSelectedNavigationItem(5);
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
});
}
public String getTab(Tab tab) {
return tab.getText().toString();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public String getCurrentDate(int offset) {
String calAsString;
DateFormat formatter = new SimpleDateFormat("MM/dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, offset);
calAsString = formatter.format(cal.getTime());
return calAsString;
}
}
Here is my FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
ArrayList<TopRatedFragment> myList;
public TabsPagerAdapter(FragmentManager fm, ArrayList<TopRatedFragment> myList) {
super(fm);
this.myList = myList;
}
#Override
public Fragment getItem(int index) {
return myList.get(index);
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return myList.size();
}
And here is my simple fragment (for now):
public class TopRatedFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void getTabs(String tabs) {
Log.e("TRF", tabs);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
Create a static newInstance method to create fragment and bundle the args for the fragment. Pull the args in the fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (String tab_name : tabs) {
TopRatedFragment fm = new TopRatedFragment.newInstance(tab_name);
fm.getTabs(tab_name);
myFragmentList.add(fm);
}
public class TopRatedFragment extends Fragment {
public static Fragment newInstance(String position) {
TopRatedFragment f = new TopRatedFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("num", position);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle b = getArguments();
if (b!=null){
String someText = b.containsKey("num")?b.getString("num"):null;
}