Looking for ?

Translate

How to call a method inside a fragment from an Activity class

     If you are having issues communicating with any method you have inside a class extending a Fragment from and AppCompatActivity or any other activity.
 NOTE: What ever you see in operaminitech is what i have solved personally. so if it didn't work for you, you check your self well.

SOLUTION:
All you need is to set a tag to the fragment when you want to get or add it into an Arraylist like below. then call it using the same tag name and then call the method.

FRAGMENT

public class Home extends Fragment {
 
//after onCreate view method 
 
//method to call from activity
public void fetchNewRssNewInstance() {

if (networkInfo.isNetworkAvailable() == true) {
empty_view.setVisibility(View.GONE);
Readrss rss = new Readrss(getActivity(), recyclerView, empty_view);
rss.execute();
recyclerView.setVisibility(View.VISIBLE);
} else {
empty_view.setText("No network connection.");
empty_view.setVisibility(View.VISIBLE);
}
 
 







ACTIVITY CLASS


public class MainActivity extends AppCompatActivity {
 
//Loading first Fragment as defaultFragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, listFragments.get(0),"externalFragTag").commit();

 
 
// I WILL CALL THE OUTSIDE METHOD WHEN A FRESH ICON BUTTON IS CLICKED FROM MENU
 
@Overridepublic boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_refresh:
// R.id.action_refresh.; FragmentManager frag = getSupportFragmentManager();
Home f = (Home) frag.findFragmentByTag("externalFragTag");
f.fetchNewRssNewInstance();

break

 
......
......
......
.....
}
 
}

 
 

SHARE THIS POST

About Wakabia

    Blogger Comment
    Facebook Comment

1 comments: