Fragment-Fragment communication in Android

前端 未结 6 1226
太阳男子
太阳男子 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:32

    Its actually pretty easy, just follow these steps:

    1. So you created the two fragments A and B, now create their brains, i.e, Java class files. Lets call them JClass A (for Fragment A) and JClass B(for Fragment B)

    2.You got button in you Frag A, so go to JClass A, and in that get the String text the user types and the button pressed event like this: // just override the onCreate method.

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.,container,false);
    
        userInput = (EditText)view.findViewById(R.id.);
    
        Button myButton = (Button)view.findViewById(R.id.);
        myButton.setOnClickListener(
                new Button.OnClickListener(){
                    public void onClick(View v){
                        JClassB.setText(userInput.getText().toString());/*Replace JClassB with the java class of Fragment B*/
    
                    }
                }
        );
    
        return view;
    }
    
    1. And finally in your JClass B(java file for fragment B):

      public class BottomSectionFrag extends Fragment {

      private static TextView userText;
      @Nullable
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.fragmentB, container, false);
          userText = (TextView)view.findViewById(R.id.userText);
          return view;
      }
      public static void setText(String text){
          userText .setText(text);
      
      }
      

      }

    Voila!!

    P.S. This is my first ever post on stackOverFlow :D

    Peace Out.

提交回复
热议问题