Getting EditText Value from a Fragment in main Activity

后端 未结 3 1074
攒了一身酷
攒了一身酷 2021-01-26 02:55

I have placed three edit text in a fragment and want to get the values of the edit text in the fragment from the main activity. I tried the following code but its throwing

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 03:11

    The thing is f1 = new Fragment1(); you have just created a object for fragment class, but this is not the exact way to call the fragment. You are supposed to set transition using the fragmentManager. If you didn't set in this way, then the frgament Lifecycle method's won't be called. So, in your scenario onCreateView() won't be called and the views are not initialized(As your stackTrace clearly states the view is not initialized). Try the below code

    f1 = new MainFragment();
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_frame, f1, 
    f1 .getClass().getSimpleName()).addToBackStack(null).commit();
    

    I hope you are aware of the other fragment container.i.e., having a FrameLayout in MainActivity and adding the Fragment to that container.

    Hope this is helpful:)

提交回复
热议问题