Send data from activity to fragment in Android

前端 未结 20 2709
悲哀的现实
悲哀的现实 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:27

    Also You can access activity data from fragment:

    Activity:

    public class MyActivity extends Activity {
    
        private String myString = "hello";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
            ...
        }
    
        public String getMyData() {
            return myString;
        }
    }
    

    Fragment:

    public class MyFragment extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            MyActivity activity = (MyActivity) getActivity();
            String myDataFromActivity = activity.getMyData();
            return view;
        }
    }
    

提交回复
热议问题