How to pass result from second fragment to first fragment

前端 未结 4 1348

In my app I have two fragments say fragmentA and FragmentB. When I click on a button in fragmetA, a list is opened in

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 18:51

    In fragmentB.java set an OnClickListener to perform a method in the main class. Pass an arguement in fragmentB.java to the main class that is the variable, and handle the rest of it in your main class. Though fragments shouldn't really be dependent on activities at all. Fragments were made to plug and play anywhere.

    This Example Shows EditTextListener:

    myAwesomeActivity.java

    fragmentA.java

    fragmentB.java

    fragmentB.java:

    @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);
                int x = 3;
    
            EditText ed1 = (EditText) getView().findViewById(R.id.editText1);
            ed1.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (MotionEvent.ACTION_UP == event.getAction()) {
    
    
    
                        ((myAwesomeActivity) getActivity()).myMethod(x);
                    }
                    return false;
                }
            });
        }
    

    myAwesomeActivity.java:

    publiv void myMethod (int x){
    //Do whatever you want with variable
    }
    

    All you have to do is implement the correct type of listener, but the main point is shown. In one fragment activity, call a method and pass a variable to the main activity. From the main activity you can send it to your other fragment activity if you'd like.

提交回复
热议问题