Android - Passing value from ListFragment to another ListFragment

后端 未结 4 476
借酒劲吻你
借酒劲吻你 2021-01-24 07:14

I have a listview containing Category of items. When I press a category title on the list, it will display another listview containing items inside the chosen Category.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-24 08:12

    You should use Interface, it's the "official" way to pass values to Fragment. Take a look at this documentation here :

    http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

    So what you need to do :

    FragmentA --> Activity --> FragmentB

    An invisible TextView is definitely not the correct solution...

    EDIT A more detailed solution :

    You define an interface (in a separate file or in your FragmentA class) :

    public interface MyFragmentListener {
        public void onFragmentItemSelected(String url);
    }
    

    in your FragmentA class :

    MyFragmentListener myListener;
    
    public void setMyFragmentListener(MyFragmentListener listener) {
        myListener = listener;
    }
    
    // here I used the onClick method but you can call the listener whereever you like.
    public void onClick(View view) {
        if (myListener != null) {
            myListener.onFragmentItemSelected(url);
        }
    } 
    

    Declaration your FragmentB class :

    public class FragmentB extends Fragment implements MyFragmentListener {
    
    
        public void onFragmentItemSelected(String url) {
            // do what you want to do
        }
    
    
    }
    

    in your Activity :

    // you tell your fragmentA that his listener is the FragmentB. And because you implemented the listener in FragmentB, everything is allright;
    fragmentA.setMyFragmentListener(fragmentB));
    

提交回复
热议问题