push data from Fragment to Fragment - android

I am new to Android. Please excuse me if it's a silly question:
If i click on button of a Fragment - it has to trigger a test and show the result in other Fragment. So to make things simple, have written a code on button click as follows. It's not working. Please suggest.
My actual intent is to register a log.add BroadcastReceiver, so that anywhere any log error or debug is called, that message has to appear in the TestStatusFragment.
public class TriggerTestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trigger, container, false);
Button stopScheduler = (Button) view.findViewById(R.id.testButton);
stopScheduler.setOnClickListener((View sview) -> {
View teststatusView = inflater.inflate(R.layout.fragment_teststatus, container, false);
TextView textView = (TextView) teststatusView.findViewById(R.id.text_view);
textView.setText("test result....");
});
return view;
}
}
MainActivity.java
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TriggerTestFragment(), "TRIGGERTEST");
adapter.addFragment(new TestStatusFragment(), "TEST STATUS");
viewPager.setAdapter(adapter);
}
Second Fragment:
public class TestStatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teststatus, container, false);
return view;
}
}

Use interface to communicate between them.
Fragment One
public class FragOne extends Fragment {
EditText etxtName, etxtDesc;
Button btnSubmit;
String name, desc;
private OnFragmentInteractionListener mListener;
public FragOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_one, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etxtName = (EditText) view.findViewById(R.id.etxtName);
etxtDesc = (EditText) view.findViewById(R.id.etxtDesc);
btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxtName.getText().toString().trim();
desc = etxtDesc.getText().toString().trim();
if(name == null || desc == null) {
Toast.makeText(getActivity(), "Both fields required", Toast.LENGTH_SHORT).show();
} else {
mListener.onFragmentInteraction(name, desc);
etxtName.setText("");
etxtDesc.setText("");
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String name, String desc);
}
}
Fragment Two
public class FragTwo extends Fragment implements FragOne.OnFragmentInteractionListener{
TextView textView, textDesc;
public FragTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_frag_two, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(R.id.txtName);
textDesc = (TextView) view.findViewById(R.id.txtDesc);
}
#Override
public void onFragmentInteraction(String name, String desc) {
textView.setText(name);
textDesc.setText(desc);
}
}
Init fragments
fragOne = new FragOne();
fragTwo = new FragTwo();
PagerAdapter
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
MainActivity need implement onFragmentInteraction interface
public class MainActivity extends AppCompatActivity implements FragOne.OnFragmentInteractionListener{
static FragOne fragOne;
static FragTwo fragTwo;
MyPagerAdapter myPagerAdapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragOne = new FragOne();
fragTwo = new FragTwo();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
#Override
public void onFragmentInteraction(String name, String desc) {
myPagerAdapter.onFragmentInteraction(name, desc );
}
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
}
You can read full article here https://www.mytrendin.com/passing-data-between-fragments/

Related

Android - Pass "edit text" element value between tabbed fragments

I have an activity with multiple swipe tabbed fragments. Each fragment has some check-boxes, edit text and switch fields. What I want is to navigate through all the tabs, edit the state of the fields then on last tab to collate the information within all the elements and save these details into a database.
My problem is that I don't know how to save these elements values and pass them to my last tab in order to be stored.
I am quite a newbie with Android apps so any hint or answer would be very much appreciated.
Here is how code looks so far:
Activity:
public class IconTextTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts,
R.drawable.ic_vector_test
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
Bundle b = getIntent().getExtras();
String id = b.getString("id");
Toast.makeText(this, id, Toast.LENGTH_LONG).show();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[2]);
tabLayout.getTabAt(4).setIcon(tabIcons[3]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
adapter.addFrag(new FourFragment(), "FOUR");
adapter.addFrag(new FiveFragment(), "FIVE");
viewPager.setAdapter(adapter);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
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);
}
}
Tab Fragment 1
public class OneFragment extends Fragment {
private EditText mBreedName;
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_one, container, false);
mBreedName = (EditText) v.findViewById(R.id.addName);
return v;
}
Tab Fragment 2
public class TwoFragment extends Fragment {
public TwoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, container, false);
return v;
}
Assuming that Tab Fragment 2 is my last tab, how could I retrieve here the text value for "mBreedName" stored into Tab Fragment 1?
Thanks!
You can store the values in your activity and use a callback to update and query them.
Try this:
On your activity:
public class IconTextTabsActivity extends AppCompatActivity implements ActivityCallback{
private String mBreedTextName = "";
...
#Override
public void onEditTextChange(String text) {
this.mBreedTextName = text;
}
#Override
public String getEditTextName() {
return mBreedTextName;
}
}
The ActivityCallback interface:
public interface ActivityCallback {
void onEditTextChange(String text);
String getEditTextName();
}
then on your fragment:
public class OneFragment extends Fragment {
...
private ActivityCallback callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
callback = (ActivityCallback) context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_one, container, false);
mBreedName = (EditText) v.findViewById(R.id.addName);
Button b = v.findViewById(R.id.accept_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callback.onEditTextChange(mBreedName.getText().toString());
}
});
return v;
}
}
And the same on the second fragment:
public class TwoFragment extends Fragment {
...
private ActivityCallback callback;
private String text;
#Override
public void onAttach(Context context) {
super.onAttach(context);
callback = (ActivityCallback) context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_two, container, false);
text = callback.getEditTextName();
return v;
}
}

android onClick change fragment

I want to change the Fragment when i click the button. The fragments are in the same adapter/viewpager.
FROM THIS FRAGMENT:
public class LoginFragment extends Fragment {
TextView linkToRegister;
public static final LoginFragment newInstance()
{
LoginFragment mf = new LoginFragment();
Bundle bd = new Bundle(1);
mf.setArguments(bd);
return mf;
}
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState )
{
View v = inflater.inflate(R.layout.fragment_login, container, false);
linkToRegister = (TextView) v.findViewById(R.id.link_to_register);
linkToRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Change Fragment
}
});
return v;
}
}
TO THIS FRAGMENT:
public class RegisterFragment extends Fragment {
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final RegisterFragment newInstance()
{
RegisterFragment mf = new RegisterFragment();
Bundle bd = new Bundle(1);
mf.setArguments(bd);
return mf;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
{
View v = inflater.inflate(R.layout.fragment_register, container, false);
return v;
}
}
PagerAdapter:
public class WelcomePagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> Welcomefragments;
public WelcomePagerAdapter(FragmentManager fm, List<Fragment> Welcomefragments) {
super(fm);
this.Welcomefragments = Welcomefragments;
}
#Override
public Fragment getItem(int position) {
return this.Welcomefragments.get(position);
}
#Override
public int getCount() {
return this.Welcomefragments.size();
}
}
Activity:
public class WelcomeActivity extends AppCompatActivity {
ViewPager welcomeViewPager;
WelcomePagerAdapter welcomePagerAdapter;
List<Fragment> welcomeFragments;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
welcomeViewPager = (ViewPager) findViewById(R.id.viewPagerWelcome);
welcomeFragments = getWelcomeFragments();
welcomePagerAdapter = new WelcomePagerAdapter(getSupportFragmentManager(), welcomeFragments);
welcomeViewPager.setAdapter(welcomePagerAdapter);
}
public List<Fragment> getWelcomeFragments() {
List<Fragment> newFragment = new ArrayList<Fragment>();
newFragment.add(LoginFragment.newInstance());
newFragment.add(RegisterFragment.newInstance());
return newFragment;
}
}
Step 1: Define a callback interface in the Fragment and hook in the Activity when the Fragment attaches to it.
public class MyFragment extends Fragment {
public interface OnInteractionListener {
void doAction(); // Can include parameters here if needed
}
private OnInteractionListener listener;
#Override
public void onAttach(Context context) {
if (context instanceof OnInteractionListener) {
listener = (OnInteractionListener) context;
} else {
throw new ClassCastException(context + "must implement " + OnInteractionListener.class.getSimpleName());
}
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// ...
return v;
}
}
Step 2: Make sure your Activity implements that Interface
public class MyActivity extends AppCompatActivity implements MyFragment.OnInteractionListener {
#Override
public void doAction() {
// TODO: Implement this... e.g. switch fragments
}
...
}
Step 3: Inside the Fragment, you can invoke the callback whenever you want to perform some action
if (listener != null) {
listener.doAction();
}
From MainActivity(), get the navController and then use the navigate() function:
NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);
navController.navigate(R.id.nav_grid);

Same fragment with different contents in viewpager

I have one parent fragment where there is viewpager and tablayout.
Viewpager holds the fragment with different contents associated with it.
Every think works fine on swipe but whenever I tap on the different tabs of the tablayout, categoryId and categoryName of SwipableFragment is changed to adjacent tab's SwipableFragmet to the visible fragment.
Basically when I launch my FragmentAllNews (containing a ViewPager) it's shown the second fragment/page instead of the first and when I swipe to the second I see the third... In other words It's always shown the next or the previous fragment/page depending on the swipe direction (left or right).
Sorry For my bad english :(
here are my Fragments and FragmentStatePagerAdater class
###1 FragmentAllNews which holds the viewpager and tablayout
public class FragmentAllNews extends Fragment {
#Bind(R.id.tab_layout)
TabLayout tabLayout;
#Bind(R.id.all_news_viewpager)
ViewPager viewPager;
SessionManager sessionManager;
String categoryId;
String categoryName;
ArrayList<TabModel> tabs;
public static FragmentAllNews createNewInstance() {
FragmentAllNews fragmentAllNews = new FragmentAllNews();
return fragmentAllNews;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
tabs = sessionManager.getSwitchedNewsValue() == 0 ?
StaticStorage.getTabData(0) :
StaticStorage.getTabData(1);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_all_news, container, false);
ButterKnife.bind(this, fragmentView);
return fragmentView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setViewPager(tabs);
setTabLayout();
}
private void setTabLayout() {
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setViewPager(ArrayList<TabModel> tabs) {
ArrayList<NewsFragmentModel> frags = new ArrayList<>();
for (int i = 0; i < tabs.size(); i++) {
if (i == 0) {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(FragmentBreakingAndLatestNews.createNewInstance(categoryId, categoryName), categoryName));
} else {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(SwipableFragment.createNewInstance(categoryId, categoryName), categoryName));
}
}
NewsPagerAdapter adapter = new NewsPagerAdapter(getChildFragmentManager(),frags);
viewPager.setAdapter(adapter);
}
#Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
###2 SwipableFragment which the fragment attached to the viewpager
public class SwipableFragment extends Fragment implements NewsTitlesAdapter.RecyclerPositionListener {
#Bind(R.id.recycler_view)
RecyclerView recyclerView;
#Bind(R.id.progess)
ProgressBar progressBar;
#Bind(R.id.cat_id)
TextView categoryTextView;
ArrayList<NewsObj> newsObjs;
NewsTitlesAdapter newsTitlesAdapter;
SessionManager sessionManager;
private static String categoryId;
private static String categoryName;
public static SwipableFragment createNewInstance(String category_id, String category_name) {
SwipableFragment swipableFragment = new SwipableFragment();
Bundle box = new Bundle();
box.putString(StaticStorage.NEWS_CATEGORY_ID, category_id);
box.putString(StaticStorage.NEWS_CATEGORY, category_name);
swipableFragment.setArguments(box);
return swipableFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
categoryId = getArguments().getString(StaticStorage.NEWS_CATEGORY_ID);
categoryName = getArguments().getString(StaticStorage.NEWS_CATEGORY);
newsObjs = (sessionManager.getSwitchedNewsValue() == 0) ?
NewsData.getNewsRepublica(getActivity()) :
NewsData.getNewsNagarik(getActivity(),categoryName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipable, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("category", categoryId + " " + categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
newsTitlesAdapter = new NewsTitlesAdapter(newsObjs);
newsTitlesAdapter.setOnRecyclerPositionListener(this);
recyclerView.setAdapter(newsTitlesAdapter);
recyclerView.addOnScrollListener(new EndlessScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Log.i("categoryId", categoryId+" "+categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ArrayList<NewsObj> moreNews = sessionManager.getSwitchedNewsValue() == 0 ?
NewsData.getNewsRepublica(getContext()) :
NewsData.getNewsNagarik(getContext(),categoryName);
int curSize = newsTitlesAdapter.getItemCount();
newsObjs.addAll(moreNews);
newsTitlesAdapter.notifyItemRangeInserted(curSize, newsObjs.size() - 1);
progressBar.setVisibility(View.GONE);
}
}, 5000);
}
});
}
#Override
public void onChildItemPositionListen(int position, View view) {
if (view.getId() == R.id.news_share_text_view) {
} else if (view.getId() == R.id.news_show_detail_text_view) {
} else {
Intent newsDetailIntent = new Intent(getActivity(), NewsDetailActivity.class);
NewsObj newsObj = newsObjs.get(position);
newsObj.setNewsCategory(categoryName);
newsDetailIntent.putExtra(NewsDetailActivity.NEWS_TITLE_EXTRA_STRING, newsObj);
startActivity(newsDetailIntent);
}
}
}
###3 NewsPagerAdapter is the subclass extended from FragmentStatePagerAdapter
public class NewsPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<NewsFragmentModel> frags;
public NewsPagerAdapter(FragmentManager fm) {
super(fm);
}
public NewsPagerAdapter(FragmentManager fm,ArrayList<NewsFragmentModel> frags){
super(fm);
this.frags = frags;
}
#Override
public Fragment getItem(int position) {
return frags.get(position).getFrag();
}
#Override
public int getCount() {
return frags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return frags.get(position).getTitle();
}
}
###4 NewsFragmentModel
public class NewsFragmentModel {
private Fragment frag;
private String title;
public NewsFragmentModel(Fragment frag, String title) {
this.frag = frag;
this.title = title;
}
public Fragment getFrag() {
return frag;
}
public void setFrag(Fragment frag) {
this.frag = frag;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Am I doing any mistakes ? please help me.If you need more info please let me know. My final hope is Stackoverflow

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"

Two instances of the same ListFragment in one FragmentActivity using ViewPager

I have a FragmentActivity that uses a ViewPager to flip left and right through pages of data (two ListFragments).
public class StopsActivity extends FragmentActivity {
private ViewPager mViewPager;
private PagerTabStrip mPagerTabStrip;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stops);
mPagerTabStrip =(PagerTabStrip)findViewById(R.id.pager_header);
mViewPager = (ViewPager)findViewById(R.id.pager);
mPagerTabStrip.setDrawFullUnderline(true);
mPagerTabStrip.setTabIndicatorColorResource(R.color.pagerTabStrip);
mViewPager.setAdapter(new StopsAdapter(getSupportFragmentManager()));
mViewPager.setCurrentItem(0);
}
private class StopsAdapter extends FragmentPagerAdapter {
public StopsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return StopsFragment.newInstance(routename, Stop.FORWARD);
case 1:
return StopsFragment.newInstance(routename, Stop.BACKWARD);
}
return null;
}
#Override
public int getCount() { return 2;}
#Override
public CharSequence getPageTitle(int position) { /* implementation ... */}
}
}
Everything runs ok, but I think that the instantation of the second StopFragment invalidate the data of the first one when getItem is called.
public class StopsFragment extends ListFragment {
private StopsAdapter mStopsAdapter;
private ListView mListView;
private String routename;
private int direction;
public static StopsFragment newInstance(String routename, int direction) {
StopsFragment stopsFragment = new StopsFragment();
// Supply arguments
Bundle args = new Bundle();
args.putString("routename", routename);
args.putInt("direction", direction);
stopsFragment.setArguments(args);
return stopsFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the adapter
ArrayList<Stop> stops = ...
mStopsAdapter = new StopsAdapter(getActivity(), stops);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_stops, container, false);
// Attach the adapter
mListView = (ListView) rootView.findViewById(android.R.id.list);
mListView.setAdapter(mStopsAdapter);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
The page "IDA" corresponds to StopFragment with argument Stop.FORWARD and the page "VUELTA" corresponds the StopFragment with argument Stop.BACKWARD. As you can see in the images below, just one of them (the last one instantiate) is populated:
What I'm doing wrong?
EDIT
This is StopsAdapter
class StopsAdapter extends BaseAdapter {
private ArrayList<Stop> stops;
private LayoutInflater inflater;
public StopsAdapter(Context context, ArrayList<Stop> stops) {
this.stops = stops;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stops.size();
}
#Override
public Object getItem(int position) {
return stops.get(position);
}
#Override
public long getItemId(int position) {
return (long)position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_stop, parent, false);
}
TextView name = (TextView)convertView.findViewById(R.id.tvStopName);
TextView description = (TextView)convertView.findViewById(R.id.tvStopDescription);
Stop stop = (Stop)getItem(position);
name.setText(stop.name);
if (stop.info != null) {
description.setText(stop.info);
}
return convertView;
}
}
Ok, my fault. The code that was giving me problems is the only that I haven't posted (ArrayList<Stop> stops = ...). The code about Fragments and ViewPager works correctly.

Categories

Resources