I have an activity and two fragments. Im trying to get a clicked item from an arraylist. In my fragmentA I have a interface:
public interface GroupListener {
public String onGroupSelected(String groupName);
}
and
@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!");
}
}
This gets the postion from an item clicked in a list:
public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
groupListener.onGroupSelected((String) getListAdapter().getItem(position));
}
I then have the listner in my activity and in fragmentB which looks the same:
@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;
}
But when i click an item only the listener in my activity is activated, not the one in my fragment. What is it that im missing?
The one in FragmentB
will not fire, since you are only communicating with the activity from fragment A.
In your activity do something like this:
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;
}
This is how you call methods inside fragment from an activity
It is a little late to answer but I found a way that works for me. As listener will first get by activity, you can define destination fragment in the Main activity and then call a method in the destination fragment and do what you want:
In the main Activity listener
DestinationFragment fragment = (DestinationFragment) getSupportFragmentManager().findFragmentById(R.id.destination_fragment);
fragment.sampleListener(bundle);
In the destination fragment define sampleListener and write your code.
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.