Call a Fragment method from an Adapter

前端 未结 3 438
长发绾君心
长发绾君心 2020-12-07 20:24

I have a method sendData() in my fragment. This method starts a new Activity. I want to call this method from my ArrayAdapter.

Here is my c

相关标签:
3条回答
  • 2020-12-07 21:02

    You can make sendData method as static

    public static void sendData(int position)
    {
         ......
    }
    

    n call it as

    @Override
    public void onClick(View v) 
    {
         // TODO Auto-generated method stub
         HomeFragment.sendData(position)
         ........    
    }
    
    0 讨论(0)
  • 2020-12-07 21:08

    Edit : Here is what I would use now. Older, "easier" solutions are available below.

    MyFragment extends Fragment implements CustomAdapter.EventListener {
    
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
            CustomAdapter adapter = new CustomAdapter(..., this);
    
        }
    
        void onEvent(int data) {
            doSomething(data);
        }
    
    }
    
    CustomAdapter extends BaseAdapter {
    
        EventListener listener; 
    
        public interface EventListener {
            void onEvent(int data);   
        }
    
        public CustomAdapter(..., EventListener listener) {
            this.listener = listener; 
        }
    
        ...
    
    }
    

    Now from any place in the adapter we can call listener.onEvent(data); to trigger the method in the fragment.

    Moreover, instead of providing a listener through the constructor, we can add another method in the adapter such as registerListener(EventListener eventListener) and then maintain a list of listeners if needed.

    Old Answer:

    Solution 1 : Make the adapter an inner class of your fragment, so that you can call the method directly.

    Solution 2 : Update your adapter constructor to accept the Fragment as a parameter.

    Something like :

    customAdapter = new CustomAdapter(myContext, android.R.layout.simple_list_item_1, getList, HomeFragment.this);
    

    and update the constructor of the Adapter :

    public CustomAdapter(Context context, int id, HomeFragment fragment) {
        this.fragment = fragment;
    }
    

    then you call methods using the fragment variable.

    fragment.doSomething();
    
    0 讨论(0)
  • 2020-12-07 21:12

    I know it's late to answer but There are 2 ways more to do it:

    1. You can also send broadcast from adapter and register it in fragment.

    2. Use interface. Refer this SO question for details.

    0 讨论(0)
提交回复
热议问题