Send data from activity to fragment in Android

前端 未结 20 2705
悲哀的现实
悲哀的现实 2020-11-21 05:13

I have two classes. First is activity, second is a fragment where I have some EditText. In activity I have a subclass with async-task and in method doInBa

20条回答
  •  别跟我提以往
    2020-11-21 05:35

    If an activity needs to make a fragment perform an action after initialization, the easiest way is by having the activity invoke a method on the fragment instance. In the fragment, add a method:

    public class DemoFragment extends Fragment {
      public void doSomething(String param) {
          // do something in fragment
      }
    }
    

    and then in the activity, get access to the fragment using the fragment manager and call the method:

    public class MainActivity extends FragmentActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            DemoFragment fragmentDemo = (DemoFragment) 
                getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
            fragmentDemo.doSomething("some param");
        }
    }
    

    and then the activity can communicate directly with the fragment by invoking this method.

提交回复
热议问题