Getting EditText Value from a Fragment in main Activity

后端 未结 3 1072
攒了一身酷
攒了一身酷 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

    f1 = new Fragment()
    

    This is not how you add fragments. You are just creating a new fragment instance here. The fragment's onCreateView never gets called because the fragment has not been added. Due to this, the editText variable is null and you get the exception. Please study fragments a little bit.

    http://www.vogella.com/tutorials/AndroidFragments/article.html

    This is how you add a fragment :

    getSupportFragmentManager().beginTransaction().add(R.id.frag_layout_id, f1, "fragment_identifier").commit();
    

    EDIT

    Since the question has been edited with the xml, although you have declared the fragment in XML, the f1 instance in your java does not refer to that. To get a handle for the instance added through xml, use this

    Fragment_Example f1 = (Fragment_Example)getSupportFragmentManager().findFragmentById(R.id.fragment);
    

提交回复
热议问题