简体   繁体   English

Android 侦听器在活动中工作但不在片段中

[英]Android Listener working in activity but not in fragment

I have an activity and two fragments.我有一个活动和两个片段。 Im trying to get a clicked item from an arraylist.我试图从 arraylist 中获取点击的项目。 In my fragmentA I have a interface:在我的片段A中,我有一个界面:

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:然后我在我的活动和片段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;
    } 

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. FragmentB中的那个不会触发,因为您只与来自 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:由于监听器将首先通过活动获取,您可以在 Main 活动中定义目标片段,然后在目标片段中调用一个方法并执行您想要的操作:
In the main Activity listener在主 Activity 监听器中

DestinationFragment fragment = (DestinationFragment) getSupportFragmentManager().findFragmentById(R.id.destination_fragment);
fragment.sampleListener(bundle);

In the destination fragment define sampleListener and write your code.在目标片段中定义 sampleListener 并编写您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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