简体   繁体   中英

Pass OnclickListener from activity to fragment inside ViewPager

I used ViewPager and Fragment in my project. The activity that contains the ViewPager has toolbar . The toolbar has set of icons that operate some actions on data that loaded in fragment. So my problem is how to find that the icon in activity clicked inside the fragment. One of solutions I think is creating a custom listener and pass it to the adapter. When the listener calls adapter again calls another listener inside the fragment but I think it's not such a good way to do that.

In the adapter maintain a hashmap of the fix cache size as of your adapter(3 by default). Keep adding and deleting instance of your fragment when you add or delete a fragment.

In the click method in activity, get the current fragment using the hashmap and perform the task by calling a method.

Let me know if you want the code implementation for this

((MyActivity) getActivity()).myOnClickMethod();

This works as well. So you don't need to add any listeners.

Also you can do something like :

public class MyActivity extends Activity implements FragmentClickedListener{
}

and in fragment gose: ((FragmentClickedListener) getActivity()).myOnClickMethod();

in this case FragmentClickedListener looks like this:

public interface FragmentClickedListener{
void myOnClickMethod();
}

Maybe this isn't the best way out, but it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM