![](/img/trans.png)
[英]Android activity fragment listener not working on clicking middle tab in tablayout
[英]Android Listener working in activity but not in fragment
我有一个活动和两个片段。 我试图从 arraylist 中获取点击的项目。 在我的片段A中,我有一个界面:
public interface GroupListener {
public String onGroupSelected(String groupName);
}
和
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
try {
groupListener = (GroupListener) context;
} catch (ClassCastException e)
{
throw new ClassCastException(context.toString() + " must implement the interface" +
"called GroupListener!");
}
}
这从列表中单击的项目中获取位置:
public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
groupListener.onGroupSelected((String) getListAdapter().getItem(position));
}
然后我在我的活动和片段B 中有一个监听器,它看起来是一样的:
@Override
public String onGroupSelected(String groupName) {
System.out.println("in onGroup in Activity");
return groupName;
}
@Override
public String onGroupSelected(String groupName) {
System.out.println("in onGroup in fragmentB");
return groupName;
}
但是当我单击一个项目时,只有我活动中的监听器被激活,而不是我的片段中的监听器。 我错过了什么?
FragmentB
中的那个不会触发,因为您只与来自 Fragment A 的活动进行通信。
在您的活动中执行以下操作:
Override
public String onGroupSelected(String groupName) {
System.out.println("in onGroup in Activity");
FragmentB frag = //find your fragment using fragment manager
frag.onGroupSelected(groupName);
return groupName;
}
这是您从活动中调用片段内部方法的方式
回答有点晚了,但我找到了一种适合我的方法。 由于监听器将首先通过活动获取,您可以在 Main 活动中定义目标片段,然后在目标片段中调用一个方法并执行您想要的操作:
在主 Activity 监听器中
DestinationFragment fragment = (DestinationFragment) getSupportFragmentManager().findFragmentById(R.id.destination_fragment);
fragment.sampleListener(bundle);
在目标片段中定义 sampleListener 并编写您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.