[英]Pass OnclickListener from activity to fragment inside ViewPager
I used ViewPager
and Fragment
in my project. 我在项目中使用了
ViewPager
和Fragment
。 The activity that contains the ViewPager
has toolbar
. 包含
ViewPager
的活动具有toolbar
。 The toolbar
has set of icons that operate some actions on data that loaded in fragment. toolbar
有一组图标,可对片段中加载的数据进行一些操作。 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). 在适配器中,维护适配器的修订缓存大小的哈希图(默认为3)。 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. 在活动中的click方法中,使用哈希图获取当前片段,然后通过调用方法来执行任务。
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();
并在片段gose中:
((FragmentClickedListener) getActivity()).myOnClickMethod();
in this case FragmentClickedListener
looks like this: 在这种情况下,
FragmentClickedListener
如下所示:
public interface FragmentClickedListener{
void myOnClickMethod();
}
Maybe this isn't the best way out, but it works. 也许这不是最好的出路,但是可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.