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>
Related
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 = "";
:)
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
}
}
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 would like to create a new fragment every time when I click its tab.
I tried to get the tab and to create a fragment. But it doesn't seem to work.
Here is my code.
Main Activity
public class MainActivity extends FragmentActivity {
private static ViewPager viewPager;
private static TabsPagerAdapter mAdapter;
private static ActionBar actionBar;
// Tab titles
private String[] tabs = { "TopRated", "Hots", "NEW"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
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(tabListener));
}
/**
* 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) {
}
});
}
static ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#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) {
}
};
TabsPagerAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new TopRatedFragment();
case 1:
return new HotStoryFragment();
case 2:
return new AllClassFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
One of the fragments
public class HotStoryFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Refresh_F","(2) HotStory");
View rootView = inflater.inflate(R.layout.fragment_hotstory, container, false);
TextView tvStudy = (TextView)rootView.findViewById(R.id.text);
return rootView;
}
I have an Action Bar with Fragment as follow. I would like to refresh current fragment using Refresh button Action Bar Menu. I saw a lot of example using getFragmentByTag() but my fragment is created dynamically. May I know how to get the current fragment and refresh the content.
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
RssFragmentPagerAdapter mRssFragmentPagerAdapter;
ViewPager mViewPager;
List<RssCategory> categoryList;
// Database Helper
private DatabaseHelper db;
private ActionBar actionBar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
db = DatabaseHelper.getInstance(getApplicationContext());
int categoryCount = db.getCategoriesCount();
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mRssFragmentPagerAdapter = new RssFragmentPagerAdapter(getSupportFragmentManager(), categoryCount);
// Set up the action bar.
actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mRssFragmentPagerAdapter);
mViewPager.setOffscreenPageLimit(categoryCount - 1);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
initialiseActionBar();
}catch(Exception e){
Log.e(getClass().getName(), e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
case R.id.action_refresh:
//TO REFRESH CURRENT Fragment
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void initialiseActionBar() {
if(categoryList == null)
categoryList = db.getAllCategories();
// For each of the sections in the app, add a tab to the action bar.
for (RssCategory category : categoryList) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(category.getName())
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class RssFragmentPagerAdapter extends FragmentPagerAdapter {
private int pageCount;
public RssFragmentPagerAdapter(FragmentManager fm, int pageCount) {
super(fm);
this.pageCount = pageCount;
}
#Override
public Fragment getItem(int i) {
switch (i) {
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new RssFragment();
Bundle args = new Bundle();
args.putInt(RssFragment.ARG_CATEGORY_ID, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return pageCount;
}
/*#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}*/
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class RssFragment extends Fragment {
public static final String ARG_CATEGORY_ID = "category_id";
View rootView;
private List<RssItem> resultList;
List<RssWebSite> websiteList;
ArrayList<String> urlList;
ProgressBar progressBar;
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try{
rootView = inflater.inflate(R.layout.fragment_rss_items_list, container, false);
resultList = new ArrayList<RssItem>();
progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
Bundle args = getArguments();
if(args != null){
DatabaseHelper db = DatabaseHelper.getInstance(rootView.getContext());
websiteList = db.getAllRssWebSiteByCategory(args.getInt(ARG_CATEGORY_ID));
urlList = new ArrayList<String>();
if(websiteList != null && websiteList.size() > 0){
for (RssWebSite website : websiteList) {
urlList.add(website.getRssUrl());
}
if(urlList.size() > 0) {
GetRSSDataTask task = new GetRSSDataTask();
task.execute(urlList);
}
}
}
}catch(Exception e){
Log.e(getClass().getName(), e.getMessage());
}
return rootView;
}
/**
* This class downloads and parses RSS Channel feed.
*
* #author clippertech
*
*/
private class GetRSSDataTask extends AsyncTask<ArrayList<String>, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(ArrayList<String>... urls) {
try {
for(String url : urls[0]) {
// Create RSS reader
RssReader rssReader = new RssReader(url);
Log.d(getClass().getName(), url);
// Parse RSS, get items
resultList.addAll(rssReader.getItems());
}
return resultList;
}catch (Exception e) {
Log.e(getClass().getName(), e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
try{
// Get a ListView from the RSS Channel view
ListView itcItems = (ListView) rootView.findViewById(R.id.rssChannelListView);
View emptyView = null;
if(result == null){
itcItems.setEmptyView(emptyView);
Log.d(getClass().getName(), "Empty View");
}
else {
//resultList.addAll(result);
Collections.sort(result, new Comparator<RssItem>() {
#Override
public int compare(RssItem lhs, RssItem rhs) {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
try {
Date date1 = formatter.parse(rhs.getPublishedDate());
Date date2 = formatter.parse(lhs.getPublishedDate());
return date1.compareTo(date2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
});
// Create a list adapter
ListAdapter adapter = new ListAdapter(rootView.getContext(), resultList);
itcItems.setAdapter(adapter);
adapter.notifyDataSetChanged();
// Set list view item click listener
itcItems.setOnItemClickListener(new ListListener(resultList, getActivity()));
}
//dialog.dismiss();
progressBar.setVisibility(View.GONE);
}catch(Exception e){
Log.e(getClass().getName(), e.getMessage());
}
}
}
}
}
You would need to keep track of the current fragment index by using the PageChangeListener in your viewpager.
You can use the fragment index to retrieve the fragment from your adapter and call whatever methods you need on it.