簡體   English   中英

Android 偵聽器在活動中工作但不在片段中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM