Get Value of different field in fragment from the parent Activity

前端 未结 4 755
借酒劲吻你
借酒劲吻你 2021-01-25 06:22

I\'ve an addActivity hosting 5 fragments, on each fragments I\'ve some fields to fill.
I want to get the value of those fields from the addActivity

4条回答
  •  滥情空心
    2021-01-25 06:55

    Do the following:

    Create interface for communicating fragment to activity:

    import android.widget.EditText;
    
    public interface FormInterface {
    
        public void returnEditedEditText(EditText editText);
    
    }
    

    The create a base fragment that instantiates the interface and overrides method for communicating when the EditText has been modified. Make sure the Fragment also implements OnEditorActionListener :

    import android.app.Activity;
    import android.app.Fragment;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.inputmethod.EditorInfo;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.TextView.OnEditorActionListener;
    
    public class FormFragment extends Fragment implements OnEditorActionListener {
    
        protected final String FRAGMENT_NAME = getClass().getName();
    
        protected FormInterface formInterface;
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
    
            //ensure activity implements interface
            try {
                formInterface = (FormInterface) activity;
            } catch (ClassCastException ex) {
                String errorString = activity.toString() + " must implement FormInterface";
                Log.e(FRAGMENT_NAME, errorString);
                throw new ClassCastException(errorString);
            }
        }
    
        @Override
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_DONE)
                formInterface.returnEditedEditText((EditText) view);
            return true;
        }
    
     }
    

    Then in make your other fragments extend the base fragment:

    YOURFRAGMENT extends FormFragment {
        //FOR EACH EDIT TEXT DO THE FOLLOWING
        EDITTEXT.setOnEditorActionListener(this);
    }
    

    Then make sure your activity implements the custom interface:

    import android.app.Activity;
    import android.widget.EditText;
    
    public class FormActivity extends Activity implements FormInterface {
    
        @Override
        public void returnEditedEditText(EditText editText) {
    
            String input = editText.getEditableText().toString();
    
            switch(editText.getId()) {
                case R.id.editText_FirstName:
                    mFirstName = input;
                    break;
                ...
            }
        }
    }
    

提交回复
热议问题