If you want to call any method of Fragment from your activity then you need to implement INTERFACE. So now I am going to introduce Interface example to Refresh a fragment list from an activity of all any method.
MainActivity File:
public class MainActivity extends Activity {
private FragmentRefreshListener fragmentRefreshListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button action_btn = (Button)findViewById(R.id.action);
action_btn .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(getFragmentRefreshListener()!= null){
getFragmentRefreshListener().onRefresh();
}
}
});
}
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
public interface FragmentRefreshListener{
void onRefresh();
}
}
Fragment File:
For doing something in your Fragment, you need to add these lines in your onCreateView() method of a fragment.
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
@Override
public void onRefresh() {
// your method
}
});
Now, you need to create a Fragment like this:
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
@Override
public void onRefresh() {
myToast();
}
});
return inflater.inflate(R.layout.fragment_advance_search, container, false);
}
public void myToast() {
Toast.makeText(context, "This is called from MainActivity", Toast.LENGTH_SHORT).show();
}
}
Write a comment