Viewpager + webservice - android

EDIT: I have found the solution.
I was casting the interface in a wrong way.
It should be:
( (IOnResultObtainedListener) adapter.getItem(i)).onResultObtained(response.getCompetition());
Instead of:
((IOnResultObtainedListener) CompetitionActivity.this).onResultObtained(response.getCompetition());
}
I have a ViewPager which contains three Fragments with a list. I need to populate them with the data I obtain when my webservice response but I don't know how to notify each Fragment. I have tried to implement an Interface between Activity and Fragments but I obtain this error:
java.lang.ClassCastException:
com.cuatroochenta.mybets.home.mygames.newGame.CompetitionActivity
cannot be cast to
com.cuatroochenta.mybets.home.mygames.newGame.IOnResultObtainedListener
Here is my Activity code:
public class CompetitionActivity extends MyBetsActionBarActivity implements ICompetitionsResponseListener {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
Handler handler;
IOnResultObtainedListener onResultObtainedListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Competiciones");
setSupportActionBar(toolbar);
handler = new Handler();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void onResume() {
super.onResume();
doRequestCompetitions();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PopularsFragment(), "Populares");
adapter.addFragment(new CategoriesFragment(), "Categorías");
adapter.addFragment(new NewsFragment(), "Nuevos");
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(adapter);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void doRequestCompetitions(){
if (NetworkUtils.isNetworkAvailable(this)) {
CompetitionsService competitionsService = new CompetitionsService();
competitionsService.setServiceUrl(url);
competitionsService.getCompetitionsAsync(new CompetitionsRequest(user, password), this);
} else {
InfoAlertManager.showInfoDialog(this, "Conexión requerida", "Aceptar");
}
}
#Override
public void onCompetitionsResponse(final CompetitionsResponse response) {
if (response.getCompetition() != null) {
Log.d("onCompetitionsResponse", response.getCompetition().toString());
// HERE IS WHEN I RECEIVE THE RESPONSE AND I SHOULD NOTIFY IT TO THE FRAGMENTS
handler.post(new Runnable() {
#Override
public void run() {
((IOnResultObtainedListener) CompetitionActivity.this).onResultObtained(response.getCompetition());
}
});
}
}
#Override
public void onError(ServiceResponseError serviceResponseError) {
Log.d("ServiceResponseError", serviceResponseError.getMessage());
}
public void setOnResultObtainedListener(IOnResultObtainedListener onResultObtainedListener){
this.onResultObtainedListener = onResultObtainedListener;
}
}
And here one of my Fragments code:
public class PopularsFragment extends Fragment implements IOnResultObtainedListener {
RecyclerView rvPopular;
CompetitionAdapter mCompetitionAdapter;
public PopularsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("PopularsFragment", "onCreate");
}
#Override
public void onStart() {
super.onStart();
Log.d("MyBets", "PopularsFragment Visible");
}
#Override
public void onResume() {
super.onResume();
((CompetitionActivity)getActivity()).setOnResultObtainedListener(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_competitions, container, false);
rvPopular = (RecyclerView) rootView.findViewById(R.id.rvCompetitions);
rvPopular.setLayoutManager(new LinearLayoutManager(getActivity()));
rvPopular.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResultObtained(Competition competition) {
mCompetitionAdapter = new CompetitionAdapter(getActivity(), competition, 0);
rvPopular.setAdapter(mCompetitionAdapter);
}
}
Any ideas? I have searched for similar questions but I haven't found anything that works...
Hope you help me. Thanks a lot!

An Interface which your CompetitionActivity implements is not IOnResultObtainedListener but ICompetitionsResponseListener. Those which implement IOnResultObtainedListener are Fragments under the ViewPager.
The instances of the Fragments are held as mFragmentList by ViewPagerAdapter. So change its modifier to default (or public) that you can access it from outside of the class.
final List<Fragment> mFragmentList = new ArrayList<>();
Also you have to keep the ViewPagerAdapter instance to a field variable instead of a local one to access it out side of the setupViewPager method:
private ViewPagerAdapter pagerAdapter;
private void setupViewPager(ViewPager viewPager) {
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
...
}
Then, instead of this line:
((IOnResultObtainedListener) CompetitionActivity.this).onResultObtained(response.getCompetition());
place this code:
for (Fragment fragment : pagerAdapter.mFragmentList) {
((IOnResultObtainedListener) fragment).onResultObtained(response.getCompetition());
}
to call each of the Fragments' listeners.

Probably, easiest would be to use an open source event bus such as Otto

Related

Check ToggleButton from Fragments

I want to use ToggleButton with tabbed activity.
I added ToggleButton to my main activity toolbar.
How can I check ToggleButton in my tabbed fragment?
this is my code on mainactivity.
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
OneFragment:
public class OneFragment extends Fragment{
public OneFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Edit:
I have added mainactivity and onefragment.
How can I check ToggleButton in onefragment?
Thank you for your help.
Edit2: github project https://github.com/jrxblu/tabtestt
Create an interface to read the ToggleButton state from Activity.
public interface ToggleButtonStateListener {
boolean isChecked();
}
Implement in Activity class
public class MainActivity extends AppCompatActivity implements ToggleButtonStateListener {
private TabLayout tabLayout;
private ViewPager viewPager;
private ToggleButton toggle;
private OneFragment oneFragment;
private TwoFragment twoFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
toggle = (ToggleButton) findViewById(R.id.togglebutton);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
oneFragment = new OneFragment();
oneFragment.setToggleListener(this);
twoFragment = new TwoFragment();
twoFragment.setToggleListener(this);
adapter.addFragment(oneFragment, "ONE");
adapter.addFragment(twoFragment, "TWO");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(oneFragment!= null) {
oneFragment.performOnCheckOperation(isChecked);
}
}
});
}
#Override
public boolean isChecked() {
return toggle.isChecked();
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Now in Fragment class whenever you need to know whether the toggle is checked or not use below code.
public class OneFragment extends Fragment{
private ToggleButtonStateListener listener;
public OneFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
boolean isToggleChecked = listener.isChecked();//call to check toggle status
Toast.makeText(getActivity(), "onCreateView: "+isToggleChecked, Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_one, container, false);
}
public void setToggleListener(ToggleButtonStateListener listener) {
this.listener = listener;
}
public void performOnCheckOperation(boolean isChecked) {
Toast.makeText(getActivity(), "performOnCheckOperation: "+isChecked, Toast.LENGTH_SHORT).show();
}
}
Two Fragment
public class TwoFragment extends Fragment{
private ToggleButtonStateListener listener;
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) {
boolean isToggleChecked = listener.isChecked();//call to check toggle status
if(isToggleChecked) {
Toast.makeText(getActivity(), ""+isToggleChecked, Toast.LENGTH_SHORT).show();
}
return inflater.inflate(R.layout.fragment_two, container, false);
}
public void setToggleListener(ToggleButtonStateListener listener) {
this.listener = listener;
}
}
If you want to perform any action directly as soon as toggle check changes. You can create a method say performOnCheckOperation inside Fragment and call that inside OnCheckedChangeListener.

in android how to put exit or close button on tabitems of an android tablayout

I have an android app with TabLayout , I create TabItems and assign them to my TabLayout Dynamically with code in my MainActivity , in one of my Fragments, which is the Fragment for a TabItem , i have a button . what I want is when that button is clicked, its TabItem closes and destroys, how can I achieve that?
extra explanation: bellow is my MainActivity.java Code ( where most of my code for creating dynamic TabItems exists :
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks {
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
viewPager.setAdapter(Adapter);
}
#Override
public void send_user_object() {
/* this is the implementation of abstract function defined
in one of my tab , in which it has a button and when
button is clicked i want the tab to be removed . */
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
List<Fragment> frag = MainActivity.this.getFragments();
return frag.size();
}
}
}
in one of my predefined tabs , i have a listview , when user clickes on an item on the list view , the detail of the item opens in a new tab , then user can see the detail by clicking on that tab . what i want is how user can close ( destroy ) that detail tab about one of items ? ( remember it is creating dynamically )
how can I remove ( close ) the TabItem with Click of a Button in that TabItem Fragment?
Plase help me , thank you beforehand .
It's not a good practice to change horizontal navigation by adding another fragment. If it's not absolutely required by your customer, create a new fragment and just replace the current one like this:
Fragment detailsFragment=new ContactsFragment()
getSupportFragmentManager.beginTransaction()
.addToBackStack("tag")
.replace(R.id.containerName, detailsFragment, "another_tag")
.commit()
At your detailsFragment your close button's clickListener just call getActivity.getSupportFragmentManager.popBackStack()
and it restores previous state.
Hope I could help you.
I solved my problem by :
first ) creating an interface in the UserDetailFragment, which you all know for communication with MainActivity, I had to do that.
but for what did I need communicating with the MainActivity ?
Answer : as you see in my code , my FragmentPagerAdapter class is defined there , and i needed my public List<Fragment> fragments = new ArrayList<>(); and public static List<String> fragmentsTitle = new ArrayList<>(); that i had saved my fragments into them , and also mytabLayout.
Seconde ) i had to define tabLayout.addOnTabSelectedListener(){} with its method OnTabSelected() , i needed that because i get the current index of the tab using addOnTabSelectedListener(){} .
Third ) i defined removeTabPage(int position) in the FragmentPagerAdapter .
Forth ) i created a method as bellow ( which is the implementation of the abstract method of UserDetailFragment interface.
#Override
public void close_tabitem() {
tabLayout.removeTabAt(tabposition_number);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tabposition_number);
Adapter.notifyDataSetChanged();
}
and here is my whole code for: MainActivity.Java
public class MainActivity extends AppCompatActivity implements ContactsFragment.CallBacks, UserDetailFragment.DetailCallBacks {
android.support.v7.widget.Toolbar toolbar;
public static List<Fragment> fragments = new ArrayList<>();
public static List<String> fragmentsTitle = new ArrayList<>();
ViewPager viewPager;
TabLayout tabLayout;
int tabposition_number;
public List<Fragment> getFragments() {
return fragments;
}
public List<String> getFragmentsTitle() {
return fragmentsTitle;
}
public void addToFragments(Fragment fragment) {
fragments.add(fragment);
}
public void addToFragmentsTitle(String title) {
fragmentsTitle.add(title);
}
public Fragment getFragmentsWithPosition(int position) {
return fragments.get(position);
}
public String getFragmentsTitleWithPosition(int position) {
return fragmentsTitle.get(position);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_drawer);
this.tabLayout = findViewById(R.id.tab_layout);
this.viewPager = findViewById(R.id.view_pager);
tabLayout.setupWithViewPager(viewPager);
SetUpViewPager(viewPager);
this.toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = findViewById(R.id.navigation_view);
navigationView.setItemIconTintList(null);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabposition_number = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public void SetUpViewPager(ViewPager viewPager) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter((getSupportFragmentManager()));
Adapter.AddFragmentPage(new SignInFragment(),"ورود");
Adapter.AddFragmentPage(new ContactsFragment(),"ارتباطات");
Adapter.AddFragmentPage(new RegisterFragment(),"ثبت نام");
viewPager.setAdapter(Adapter);
}
#Override
public void send_user_object(UserObject userObject) {
// tabLayout.removeTabAt(tabposition_number);
// myViewPagerAdapter.remove
}
#Override
public void create_user_detail_tab(UserObject userObject) {
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
UserDetailFragment userDetailFragment = new UserDetailFragment();
Bundle bundle = new Bundle();
bundle.putString("name",userObject.getName());
bundle.putString("family",userObject.getFamily());
bundle.putString("email",userObject.getEmail());
userDetailFragment.setArguments(bundle);
Adapter.AddFragmentPage(userDetailFragment,userObject.getName());
viewPager.setAdapter(Adapter);
}
#Override
public void close_tabitem() {
tabLayout.removeTabAt(tabposition_number);
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.removeTabPage(tabposition_number);
Adapter.notifyDataSetChanged();
}
public class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager manager) {
super(manager);
}
public void removeTabPage(int position) {
fragments.remove(position);
fragmentsTitle.remove(position);
notifyDataSetChanged();
}
public void AddFragmentPage(Fragment frag,String title) {
MainActivity.this.addToFragments(frag);
MainActivity.this.addToFragmentsTitle(title);
}
public Fragment getItem(int position) {
return MainActivity.this.getFragmentsWithPosition(position);
}
public CharSequence getPageTitle(int position) {
return MainActivity.this.getFragmentsTitleWithPosition(position);
}
public int getCount() {
List<Fragment> frag = MainActivity.this.getFragments();
return frag.size();
}
}
}
and here is the UserDetailFragment.Java , which acts as my TabItem :
public class UserDetailFragment extends Fragment {
View view;
DetailCallBacks detailCallBacks;
public UserDetailFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.user_detail_fragment,null);
return view;
}
#Override
public void onResume() {
super.onResume();
Button closebtn = view.findViewById(R.id.detail_close_button);
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailCallBacks.close_tabitem();
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
detailCallBacks = (DetailCallBacks)context;
}
public interface DetailCallBacks {
public void close_tabitem();
}
}
Hope It Helps You.
But do remember, you can not use this button. put the button in some other tabitem or in the menu.
or you can use :
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
to change the tabitem and then fire the event .
enjoy .....

Call a method when sliding from one fragment to another

I have 2 Tabs as fragments in a ViewPager in an Activity
When I tap the second tab in the layout, the OnTabUnselected method works.
However, when I slide the screen from one tab to another, the method isn't called.
How do I achieve this calling of method by both means "Tapping as well as in a Sliding Gesture"
My Activity class is:
public class OrderActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FloatingActionButton printAction;
ViewPagerAdapter adapter;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
TypefaceUtil.overrideFont(getApplicationContext(), "serif", "fonts/opensans.tff");
//TypefaceUtil.overrideFont(getApplicationContext(), "arial", "fonts/opensans.tff");
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
//setupTabIcons();
printAction = (FloatingActionButton) findViewById(R.id.float_print);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabSelected",Toast.LENGTH_LONG).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
String ac = null;
int pos = viewPager.getCurrentItem();
Fragment activeFragment = adapter.getItem(pos);
if(pos==0){
ac= ((PersonalDetailFragment)activeFragment).getXmlValue();
}
Toast.makeText(getApplicationContext(),ac,Toast.LENGTH_LONG).show();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabReselected",Toast.LENGTH_LONG).show();
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new PersonalDetailFragment(), "Personal");
adapter.addFrag(new OrderItemsFragment(), "Invoice");
viewPager.setAdapter(adapter);
}
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);
}
}
}
Fragment A:
public class FragmentA extends Fragment {
private EditText custName;
public PersonalDetailFragment() {
// 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 view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
custName = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
public String getXmlValue(){
return custName.getText().toString();
}
}
Fragment B:
public class FragmentB extends Fragment {
private EditText contactNo;
public PersonalDetailFragment() {
// 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 view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
contactNo = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
}
You can use the ViewPager.addOnPageChangeListener() method to register a listener and get notified about changing the current tab with a pager swipe.
There is a really nice tutorial here.
In your fragment you can use a method named setVisibilityHint that is called every time the visibility of the fragment has been changed. There is a boolean parameter that can be true or false depending if the fragment is visible or not
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}

Android - Do something every time I switch from fragments

I have an activity that has two fragments. The activity has a custom toolbar and the remaining space on the screen is used by the fragments (one at a time). In this toolbar there is a SearchView.OnQueryTextListener but this search should always be available in the fragment 1 and for the fragment 2 if should be available only if it meets a criteria. So what I need is a way to check, everytime I switch from fragments which one if occupying the screen at the moment and if it's the fragment one I set the searchView as available and for the fragment 2 the searchView will be available only if it meets the criteria.
This is my Activity:
public class ActivityTeams extends BaseActivity implements SearchView.OnQueryTextListener {
public ActivityTeams(){
super(R.layout.activity_teams);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
token = SharedPrefsHelper.getString(getApplicationContext(), Constants.TOKEN);
listview = (ListView) findViewById(R.id.listview);
listview.setVisibility(View.INVISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new InternsFragment(), getResources().getString(R.string.team_internal));
adapter.addFragment(new ExternsFragment(), getResources().getString(R.string.team_external));
viewPager.setAdapter(adapter);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
protected void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if(toolbar!=null) {
if (user_type == 1) {
toolbar.setTitle(R.string.collaborators_title);
} else if (user_type == 2) {
toolbar.setTitle(R.string.admin_title);
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_action_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search_team, menu);
SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) searchMenuItem.getActionView();
ImageView searchSubmit = (ImageView) searchView.findViewById (android.support.v7.appcompat.R.id.search_go_btn);
searchSubmit.setImageResource(R.drawable.ic_dots_w);
searchSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Clear query
searchView.setQuery("", false);
//Collapse the action view
searchView.onActionViewCollapsed();
//Collapse the search widget
searchMenuItem.collapseActionView();
listview.setVisibility(View.GONE);
viewPager.bringToFront();
appBarLayout.setVisibility(View.VISIBLE);
}
});
for (TextView textView : findChildrenByClass(searchView, TextView.class)) {
textView.setTextColor(Color.BLACK);
textView.setHintTextColor(Color.BLACK);
}
searchView.setSearchableInfo(searchManager.
getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return true;
}
This is fragment 1:
public class InternsFragment extends Fragment{
public InternsFragment() {
// 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 rootView = inflater.inflate(R.layout.fragment_interns, container, false);
return rootView;
}
And this is fragment 2:
public class ExternsFragment extends Fragment {
public ExternsFragment() {
// 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 rootView = inflater.inflate(R.layout.fragment_externs, container, false);
return rootView;
}
searchMenuItem in my activity is the thing I want to make change the visibility depending on the fragment that it's visible.
Use a ViewPager.OnPageChangeListener and use InvalidateOptionsMenu() inside that like so:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentFragment = position // use a field to store position
invalidateOptionsMenu();
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
});
Then depending on position, setup your menu in onPrepareOptionsMenu

How to call a fragment method from an activity in android?

I'm having a tabbed View, and a Floating Action Button on my Main Activity. Whenever I click on the Floating Action Button, I want to call a method that is present in my fragment's code. I tried many things, but it is saying that
Attempt to invoke virtual method 'void com.shyamzawar.makeMyResume.fragments.EducationalDetailsFragment.showChangeLangDialog()' on a null object reference
Here's my code for UserDetailsActivity :
public class UserDetailsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private int currentPage;
private FloatingActionButton fab;
private int readFileRequestCode;
private int[] tabIcons = {
R.drawable.ic_account_circle_white, //0 Personal Details
...
R.drawable.ic_create_white_36dp, //7 Declaration
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Set Title according to the user clicked
String name = "Shyam Zawar";
this.setTitle(name+"'s Profile");
fab = (FloatingActionButton) findViewById(R.id.fab);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
viewPager.addOnPageChangeListener(new DetailOnPageChangeListener());
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
fab.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (currentPage>0)
{
switch (currentPage)
{
case 1:
FragmentManager manager = getSupportFragmentManager();
EducationalDetailsFragment educationalDetailsFragment = (EducationalDetailsFragment) manager.findFragmentById(R.id.EduFragment);
educationalDetailsFragment.showChangeLangDialog();
break;
}
}
}
});
}
private void setupTabIcons()
{
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
...
tabLayout.getTabAt(7).setIcon(tabIcons[7]);
}
private void setupViewPager(ViewPager viewPager)
{
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new PersonalDetailsFragment(), " PERSONAL DETAILS"); //0
...
adapter.addFrag(new DeclarationFragment(), " DECLARATION"); //7
viewPager.setAdapter(adapter);
}
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);
}
}
}
Here is the code for EducationalDetailsFragment.java
public class EducationalDetailsFragment extends Fragment{
private FloatingActionButton fab;
private TextView TextViewEduDetails;
public EducationalDetailsFragment() {
// Required empty public constructor
}
#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_educational_details, container, false);
TextViewEduDetails = (TextView) view.findViewById(R.id.TextViewEduDetails);
return view;
}
public void setData(String stringData)
{
TextViewEduDetails.setText(stringData);
}
public void showChangeLangDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.educational_details_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Educational Details");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
You can globally declare your educationFragment
private EducationalDetailsFragment mEducationalDetailsFragment;
//in your setupViewPager() method
mEducationalDetailsFragment = new EducationalDetailsFragment();
adapter.addFrag(mEducationalDetailsFragment , "Whatever the Name");
onYourFabClickListerner(){
call the method by using mEducationalDetailsFragment
}
It seems your EducationalDetailsFragment object is null. Use this to retrieve your fragment from your viewpager. Its a better practice:
Fragment EducationalDetailsFragment = viewPager.getAdapter().getItem(index);
If you dont know the index. You can set a tag to your fragment when you create them and find them by tag from your viewpager adapter ;)
change fragment:
public void changeFragment(Fragment fragment){
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.content,
fragment).commit();
}

Categories

Resources