Fragment-Fragment communication in Android

前端 未结 6 1198
太阳男子
太阳男子 2020-11-28 10:46

I am at beginner level in Android programming, so I need your sincere help for this. Anyone help me please.

I am trying to build a SLIDING UI using fragments

6条回答
  •  抹茶落季
    2020-11-28 11:23

    It sounds as if your setup might be something like - MainActivity w/ FragmentA [added] and FragmentB [added]. For this case, I would delegate messages/actions between the two fragments through the MainActivity. Allowing MainActivity to handle the messages/actions also facilitates 'special' orchestrations which might be needed in a more complex situation between the Fragments. For example:

    public interface FragmentCommunicator
    {
        public void sendMessage ( String broadcastMessage );
        public void takeAction ( String name, int action, Fragment frag );
    }
    
    public class MainActivity extends Activity implements FragmentCommunicator
    {
        Fragment fragA;
        Fragment fragB;
        ...
        @Override
        public void sendMessage ( String msg )
        {
            if ( msg.Contains("Send To fragA") )
                fragA.receiveMsg(msg);
            ...
        }
        @Override
        public void takeAction ( String name, int action, Fragment frag )
        {
        if ( action == CLOSE )
                removeFragment( name, frag );
            ...
        }
    }
    
    public class FragmentA extends Fragment
    {
        ...
    @Override
    public void onClick(View v)
    {   
         FragmentCommunicator inter = (FragmentCommunicator) getActivity();
         inter.sendMessage("the txt/information/etc you want to send to fragB");    
    }
    }
    
    public class FragmentB extends Fragment
    {
        ...
        public void receiveMsg ( String msg )
        {
            textView.setText(msg);
        }
    }
    

    I forgot to post the send portion of FragmentA. Hope this helps.

提交回复
热议问题