how to transaction replace a fragment in tabs - android

I have an Android tabs with 3 fragments and a FAB. I want to replace to a new fragment when click the FAB but when i click the button it replace with a blank fragment. And when i click on my tabs, it doesn't show its fragment but an empty fragment instead (sometimes it show right but i don't know when)
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private TabLayout tabLayout;
private FloatingActionButton fabAdd;
FragmentManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.container);
PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager());
pageAdapter.addFragment(new Wallet(), "Wallet");
pageAdapter.addFragment(new History(),"History");
pageAdapter.addFragment(new Setting(),"Setting");
mViewPager.setAdapter(pageAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
fabAdd = (FloatingActionButton) findViewById(R.id.fabAdd);
manager = getSupportFragmentManager();
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddAccount addAccount = new AddAccount();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,addAccount);
transaction.commit();
}
});
}
}
And here is my adapter:
public class AccountAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<Account> accountList;
public AccountAdapter(Context context, int layout, List<Account> accountList) {
this.context = context;
this.layout = layout;
this.accountList = accountList;
}
#Override
public int getCount() {
return accountList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(layout,null);
TextView accountName = (TextView) view.findViewById(R.id.tvAccount);
TextView accountAddress = (TextView) view.findViewById(R.id.tvAddress);
Account account = accountList.get(i);
accountName.setText(account.getAccountName());
accountAddress.setText(account.getAccountAddress());
return view;
}
}
Here is one of my Fragments (the other is same):
public class AddAccount extends Fragment {
public AddAccount() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_account,container,false);
}
}
I'm new to Android and not good English, so forgive me if i make grammar mistake.
Edit: Is there any way to show a new fragment to a viewpager?

Use this code inside onClick
Fragment fragment = new AddAccount();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.commit();
and use this for your adapter
class AccountAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}

Related

ViewPager not showing content onResume

I'm using FragmentStatePagerAdapter for TabLayout with a ViewPager going to show a RecyclerView and when I click on a item of my list and i click back to go to previous page It's showing me a blank page with TabLayout and no RecyclerView.
Here is my Adapter code:
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And here is my fragment handling ViewPager and TabLayout:
public class InternetFragment extends Fragment {
private View rootView;
private TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_internet_package, container, false);
initUI();
return rootView;
}
private void initUI() {
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
tabLayout = rootView.findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TextView txtTabTitle = (TextView) LayoutInflater.from(GC.getInstance().getAppContext()).inflate(R.layout.custom_tablayout_cell, null);
tabLayout.getTabAt(i).setCustomView(txtTabTitle);
txtTabTitle.setTypeface(GC.font);
}
}
private void setupViewPager(ViewPager viewPager) {
String IMSI = GC.getInstance().getSimNumber();
MyViewPagerAdapter pageAdapter = new MyViewPagerAdapter(getActivity().getSupportFragmentManager());
if (IMSI.startsWith(ClientConstant.IMSI_RIGHTEL) || IMSI.startsWith(ClientConstant.IMSI_TALIA)) {
tabLayout.setVisibility(View.GONE);
pageAdapter.addFragment(new InternetOnlinePackageFragment(), "");
} else {
pageAdapter.addFragment(new InternetUSSDPackageFragment(), getString(R.string.package_ussd));
pageAdapter.addFragment(new InternetOnlinePackageFragment(), getString(R.string.package_online));
}
viewPager.setAdapter(pageAdapter);
if (!IMSI.startsWith(ClientConstant.IMSI_RIGHTEL) || !IMSI.startsWith(ClientConstant.IMSI_TALIA))
viewPager.setCurrentItem(1);
}
}

TabLayout always shows the last fragment

I am trying to fill Tablayout from 2 different fragments depending on the value (0 or 1) of the argument Radios.newInstance(int type)
The first fragment contains all radio stations and the second contains the favorite stations
But it shows me always the fragment containing the favorite stations
public class HomeFragment extends Fragment {
public static final String TAG = "HomeFragment";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ProgressBar mProgressView;
private ViewGroup mContainer;
private BaseActivity activity;
public HomeFragment() {
}
public static HomeFragment newInstance() {
return new HomeFragment();
}
public void showProgress(final boolean show) {
mContainer.setVisibility(show ? View.GONE : View.VISIBLE);
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
activity = (BaseActivity) getActivity();
activity.findViewById(R.id.tabs).setVisibility(View.VISIBLE);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
activity.getSupportActionBar().show();
mProgressView = (ProgressBar) activity.findViewById(R.id.progress);
mContainer = container;
showProgress(true);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.container);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(RadiosFragment.newInstance(0));
fragments.add(RadiosFragment.newInstance(1));
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(), fragments);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) activity.findViewById(R.id.tabs);
tabLayout.setVisibility(View.VISIBLE);
tabLayout.setTabMode(TabLayout.GRAVITY_CENTER);
tabLayout.setupWithViewPager(mViewPager);
showProgress(false);
return view;
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> mFragments;
public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "RADIOS";
case 1:
return "FAVORITES";
default:
return null;
}
}
}
}
This is the fragment that i want to show, if type == 0 it shows the all radio stations, and if type == 1 it shows the favorite stations
public class RadiosFragment extends Fragment {
private static String TYPE = "NONE";
private FirebaseRecyclerAdapter<FireBaseManager.Radio, ViewHolder> mAdapter = null;
private FirebaseRecyclerAdapter<FireBaseManager.Favorites, ViewHolder> mAdapter_fav = null;
private RecyclerView recyclerView;
public ArrayList<FireBaseManager.Favorites> listOrder;
public RadiosFragment() { }
public static RadiosFragment newInstance(int type) {
if (type == 1 )
TYPE = "favorite";
else
TYPE = "radios";
RadiosFragment fragment = new RadiosFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
final Context context = view.getContext();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
recyclerView = (RecyclerView) view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
Query query = FireBaseManager.Radio.Ref.orderByChild(FireBaseManager.Radio.Table.Name.text);
ProgressDialog progressDialog = new ProgressDialog(getContext());
if (TYPE == "favorite"){
....
#Override
protected void populateViewHolder(ViewHolder viewHolder, FireBaseManager.Favorites model, int position) {
...
viewHolder.Initialize(Data);
...
}
};
recyclerView.setAdapter(mAdapter_fav);
}
});
}
else if(TYPE == "radios") {
....
#Override
protected void populateViewHolder(ViewHolder viewHolder, FireBaseManager.Radio model, int position) {
...
viewHolder.Initialize(Data);
...
});
}
};
recyclerView.setAdapter(mAdapter);
});
}
return view;
}
}
I think the problem has to do with onCreateView / onCreate but i am no sure, can you help me please.
This might help you.
mViewPager.setCurrentItem(0);
Add this line after you setup tabLayout with viewpager
thank you very much for your answers, i have found a solution for my problem.
the solution is to add Listener on the Tablayout and intercept the events.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0)
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.flContent, RadiosFragment.newInstance(0), FavoriteActivity.TAG).addToBackStack(null).commit();
if (tab.getPosition() == 1)
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.flContent, RadiosFragment.newInstance(1), FavoriteActivity.TAG).addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

Catch the changing of slide in a ViewPager

I have implemented a ViewPager in order to swipe between two Fragments like such:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.statistics_general_vp, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mStatisticsPagerAdapter = new StatisticsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mStatisticsPagerAdapter);
return view;
}
public class StatisticsPagerAdapter extends FragmentStatePagerAdapter {
public StatisticsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new GeneralStatistics();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
But for now my two slides display the same Fragment.
How may I have slide 1 display Fragment 1 and slide 2 Fragment 2?
have u created fragment1 and fragment 2 seperately?? if yes then do this - in activity holding these two fragments.
private void createViewPager(ViewPager viewPager) {
Log.d("activity", "viewpager");
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment1(), "");
adapter.addFrag(new Fragment2(), "");
viewPager.setAdapter(adapter);
}
create fragment like this -
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.transaction_layout, container, false);
return v;
}
}
create viewpager like this -
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
or if you want to make tab with icons use this method -
private void createTabIcons() {
Log.d("activity", "createtabicons");
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabOne.setText("QR Scan");
tabOne.setTypeface(MRR);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image1, 0, 0);
tabOne.setCompoundDrawablePadding(5);
tabLayout.getTabAt(0).setCustomView(tabOne);
tabLayout.getTabAt(0).getCustomView().setSelected(true);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabTwo.setText("Mobile No.");
tabTwo.setTypeface(MRR);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image3, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
tabTwo.setCompoundDrawablePadding(5);
}
Hello i show you what i doing, i got 2 fragments in mainActivity
private void addFragments() {
List<Fragment> fragments = new ArrayList<>();
chatFragment = new ChatFragment();
remoteFragment = new RemoteFragment();
fragments.add(remoteFragment);
fragments.add(chatFragment);
MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(TAB_REMOTE_POSITION)
.setIcon(getDrawable(R.drawable.ic_settings_remote_white_24dp));
tabLayout.getTabAt(TAB_SOCIAL_POSITION)
.setIcon(getDrawable(R.drawable.ic_group_white_24dp));
}
Here is my adapter:
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
and on OnCreate u should
addFragments();
also i bind the views with ButterKnife
#Bind(R.id.view_pager)
ViewPager viewPager;
#Bind(R.id.tab_layout)
TabLayout tabLayout;
but u can static implement this with android
And remember that u have listeners:
private void pageChangeListener() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}

Custom adapter for multiple fragments in one tab of ViewPager

I want to want to make ViewPager with each tab containing three fragments. FragmentPagerAdapter only works for one fragment, so I tried my best to make my own custom adapter extending PagerAdapter. Unfortunately, the code I wrote only displays these three Fragments in the first tab and after restarting the app all tabs are blank. I suspect that it has something to do with onSaveInstanceState, but I don't know how to make it properly. Also, I've read that I shouldn't add the fragments to FragmentTransaction in instantiateItem, but I don't know where else I could do it. Could you help me ?
TaskListPagerActivity:
public class TaskListPagerActivity extends AppCompatActivity implements BottomPanelFragment.OnBottomPanelSelectedListener {
private static final String TAG = "TaskListPagerActivity";
private ViewPager mViewPager;
FragmentStacker[] mStacker;
public static Intent newInstance(Context packageContext) {
Intent intent = new Intent(packageContext, TaskListPagerActivity.class);
return intent;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_list_pager);
mStacker = new FragmentStacker[7];
mViewPager = (ViewPager) findViewById(R.id.activity_task_list_pager);
mViewPager.setAdapter(new TaskListPagerAdapter(this));
}
// Interface methods
private class TaskListPagerAdapter extends PagerAdapter {
private FragmentActivity mContext;
public TaskListPagerAdapter(FragmentActivity context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment res;
FragmentManager fm = mContext.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (mStacker[position] == null) {
mStacker[position] = new FragmentStacker();
ft.add(container.getId(), mStacker[position]);
} else {
ft.attach(mStacker[position]);
}
res = mStacker[position];
ft.commit();
return res;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 7;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView()==view;
}
}}
FragmentStacker:
public class FragmentStacker extends Fragment {
Fragment[] fragments = createFragments();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.task_list_activity_fragment, container, false);
FragmentManager fm = getFragmentManager();
Fragment customDateFragment = fm.findFragmentById(R.id.custom_date_fragment_container);
Fragment taskListFragment = fm.findFragmentById(R.id.task_list_fragment_container);
Fragment bottomPanelFragment = fm.findFragmentById(R.id.bottom_panel_container);
FragmentTransaction fragmentTransaction = fm.beginTransaction();
if (customDateFragment == null) {
customDateFragment = fragments[0];
taskListFragment = fragments[1];
bottomPanelFragment = fragments[2];
fragmentTransaction.add(R.id.custom_date_fragment_container, customDateFragment);
fragmentTransaction.add(R.id.task_list_fragment_container, taskListFragment);
fragmentTransaction.add(R.id.bottom_panel_container, bottomPanelFragment);
fragmentTransaction.commit();
} else {
fragmentTransaction.attach(customDateFragment);
fragmentTransaction.attach(taskListFragment);
fragmentTransaction.attach(bottomPanelFragment);
}
return v;
}
private Fragment[] createFragments() {
return new Fragment[]{new CustomDateFragment(), new TaskListFragment(), new BottomPanelFragment()};
}}

Calling methods between fragments

This is very simplified problem that I have regarding to Fragments and calling methods between fragments. I have put in the code place where I think calling method should be. Correct me if I'm wrong or if you have right solution for my problem. MainFragment extends Fragment because it is not activity... I have navigation drawer so that is how it suppose to be... :)
public class MainFragment extends Fragment{
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container, false);
adapter = new CategoriesPagerAdapter(getChildFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
tabs.setViewPager(pager);
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ...here I need to call method "writeText()" in both fragments to update both TextViews also in both fragments (tabs)
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Tab1Class tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
Tab2Class tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
Tab2Class:
public class Tab1Class extends Fragment {
TextView tv1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
tv1 = (TextView) rootView.findViewById(R.id.tv1);
writeText();
}
public void writeText(){
tv1.setText("TV1 text");
}
}
Tab1Class:
public class Tab2Class extends Fragment {
TextView tv2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab2, container, false);
tv2 = (TextView) rootView.findViewById(R.id.tv2);
writeText();
}
public void writeText(){
tv2.setText("TV2 text");
}
}
.
.
.
Toolbar mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar_actionbar);
final Spinner spinner_nav = (Spinner) mToolbar.findViewById(R.id.spinner_nav);
spinner_nav.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/////////////////////////Added////////////
adapter.callWrite();
////////////////////////////////////////
}
});
}
public class CategoriesPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
/////////////////////Added///////////////////
Tab1Class tab1;
Tab2Class tab2;
//////////////////////////////
public CategoriesPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
tab1 = new Tab1Class();
return tab1;
} else if (position == 1) {
tab2 = new Tab2Class();
return tab2;
} else {
return null;
}
}
////////////////////////////Added////////////////////
public void callWrite(){
if(tab1 != null)
tab1.writeText();
if(tab2 != null)
tab2.writeText();
}
/////////////
.
.
.
Here's an alternative:
public class BlankFragment extends Fragment {
public static final String ACTION_SOME_STUFF_HAPPENED = "stuff_happened_yo";
public static final String EXTRA_STUFF = "this_is_stuff";
public static void notifyStuffHappening(Context context, String stuff){
Intent intent = new Intent(ACTION_SOME_STUFF_HAPPENED);
intent.putExtra(EXTRA_STUFF, stuff);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private StuffHappenedReceiver mStuffListener;
public static class StuffHappenedReceiver extends BroadcastReceiver {
final BlankFragment mFragment;
public StuffHappenedReceiver(BlankFragment fragment) {
this.mFragment = fragment;
// listen for changes to the account we're using
IntentFilter filter = new IntentFilter(ACTION_SOME_STUFF_HAPPENED);
LocalBroadcastManager.getInstance(fragment.getContext()).registerReceiver(this, filter);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_SOME_STUFF_HAPPENED.equals(action)) {
mFragment.someStuffHappened(intent.getStringExtra(EXTRA_STUFF));
}
}
}
private void someStuffHappened(String stringExtra) {
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mStuffListener = new StuffHappenedReceiver(this);
}
#Override
public void onDetach() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mStuffListener);
mStuffListener = null;
super.onDetach();
}
}
This shows the basics of a fragment that will register a broadcast receiver automatically as it attaches / detaches from the activity.
If the fragment is not attached, it won't be updated.
To update this fragment, call the static method "notifyStuffHappening"

Categories

Resources