Trying to call a method in my activity from a fragment. I want the fragment to give the method data and to get the data when the method return. I want to achieve similar to
((KidsStoryDashboard)getActivity()).values(title_txt,bannerImgUrl);
public void values(String title_txts, String bannerImgUrl) {
if (!title_txts.isEmpty()) {
//Do something to set text
}
imageLoader.displayImage(bannerImgUrl, htab_header_image, doption);
}
For Kotlin try it out
class DataForm : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Tasks(this).getData()
}
fun getResponse(response: String) {
// code
}
}
class Tasks(private val context: Any) {
fun getData() {
val getContext = (context as DataForm).activity
val getFragment = (context as DataForm)
val responseListener = Response.Listener<String> { response ->
getFragment.getResponse(response)
}
val errorListener = Response.ErrorListener { error ->
error.printStackTrace();
}
val stringRequest = StringRequest(Request.Method.GET, url, responseListener, errorListener)
Volley.newRequestQueue(getContext).add(stringRequest)
}
}
Although i completely like Marco's Answer i think it is fair to point out that you can also use a publish/subscribe based framework to achieve the same result for example if you go with the event bus you can do the following
fragment :
EventBus.getDefault().post(new DoSomeActionEvent());
Activity:
@Subscribe
onSomeActionEventRecieved(DoSomeActionEvent doSomeActionEvent){
//Do something
}
((your_activity) getActivity).method_name()
Where your_activity
is the name of your activity and method_name()
is the name of the method you want to call.
For accessing a function declared in your Activity via your fragment please use an interface, as shown in the answer by marco.
For accessing a function declared in your Fragment via your activity you can use this if you don't have a tag or an id
private void setupViewPager(ViewPager viewPager) {
//fragmentOne,fragmentTwo and fragmentThree are all global variables
fragmentOne= new FragmentOne();
fragmentTwo= new FragmentTwo();
fragmentThree = new FragmentThree();
viewPagerAdapteradapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapteradapter.addFragment(fragmentOne, "Frag1");
viewPagerAdapteradapter.addFragment(fragmentTwo, "Frag2");
viewPagerAdapteradapter.addFragment(fragmentThree, "Frag3");
//viewPager has to be instantiated when you create the activity:
//ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
//setupViewPager(viewPager);
//Where R.id.pager is the id of the viewPager defined in your activity's xml page.
viewPager.setAdapter(viewPagerAdapteradapter);
//frag1 and frag2 are also global variables
frag1 = (FragmentOne)viewPagerAdapteradapter.mFragmentList.get(0);
frag2 = (FragmentTwo)viewPagerAdapteradapter.mFragmentList.get(1);;
//You can use the variable fragmentOne or frag1 to access functions declared in FragmentOne
}
This is the ViewpagerAdapterClass
class ViewPagerAdapter extends FragmentPagerAdapter {
public 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);
}
}
This answer is for noobs like me. Have a good day.
You should probably try to decouple the fragment from the activity in case you want to use it somewhere else. You can do this by creating a interface that your activity implements.
So you would define an interface like the following:
Suppose for example you wanted to give the activity a String and have it return a Integer:
public interface MyStringListener{
public Integer computeSomething(String myString);
}
This can be defined in the fragment or a separate file.
Then you would have your activity implement the interface.
public class MyActivity extends FragmentActivity implements MyStringListener{
@Override
public Integer computeSomething(String myString){
/** Do something with the string and return your Integer instead of 0 **/
return 0;
}
}
Then in your fragment you would have a MyStringListener variable and you would set the listener in fragment onAttach(Activity activity) method.
public class MyFragment {
private MyStringListener listener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (MyStringListener) context;
} catch (ClassCastException castException) {
/** The activity does not implement the listener. */
}
}
}
edit(17.12.2015):onAttach(Activity activity) is deprecated, use onAttach(Context context) instead, it works as intended
The first answer definitely works but it couples your current fragment with the host activity. Its good practice to keep the fragment decoupled from the host activity in case you want to use it in another acitivity.