How to pass the value of the EditText from a Fragment to the TextView of another Fragment?

4

I have a fragment containing an EditText in which the user will enter his name.

In another fragment is the TextView that will receive the name entered in the previous fragment.

Fragment Edit (where the user will type the name):

public class Editar extends Fragment implements View.OnClickListener{ 
    private EditText editar; private Button okBotao;

    View rootview;

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
        rootview = inflater.inflate(R.layout.fragment_editar, container, false);

        editar = (EditText) rootview.findViewById(R.id.editar); 
        okBotao = (Button) getActivity().findViewById(R.id.ok);

        okBotao.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) { 
                InicioActivity menu = new InicioActivity(); 
                Bundle args = new Bundle(); 
                args.putString("editar", editar.getText().toString());   
                menu.setArguments(args); 
            } 
         }); 
         return rootview;
    }
}

Home Fragment (where the name will be displayed):

public class Inicio extends Fragment { 
    TextView text; 
    View rootview;

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
        rootview = inflater.inflate(R.layout.fragment_main, container, false);

        TextView text = (TextView) rootview.findViewById(R.id.campoNome);

        Bundle bundle = getArguments();

        String editar = bundle.getString("editar");
        text.setText(editar);

        return rootview; 
    }
}
    
asked by anonymous 14.04.2015 / 20:01

1 answer

4

You are having trouble because you are assigning responsibilities to Fragment Edit that should not be his.

Fragments control associated with an Activity is your responsibility.

Each Fragment should only worry about managing your data / objects.

What you want is that when a Fragment button is pressed, Fragment have your TextView updated with the text that is in the EditText of the Fragment Edit.

As the responsibility of managing Fragments is Activity we need to find a way to notify you. The way to ensure that Activity handles this notification is to force it to implement an interface when trying to associate Fragment Edit >.

In the Edit class we declare the interface to be implemented and an attribute to save a reference to who to implement:

public class Editar extends Fragment implements View.OnClickListener{

    private OnOkButtonListener mCallback;
    public interface OnOkButtonListener{
        //Métodos que a actividade devem implementar
        onOkButtonClick(string texto);
    }

    // É sempre bom ter um Context
    private Context context;
    ....
    ....
}

In the onAttach() method, we check if the activity that is trying to associate the Fragment implements the interface and saves its reference:

@Override
public void onAttach(Activity activity) {

    if(activity instanceof OnOkButtonListener){
        mCallback = (OnOkButtonListener) activity; //Guarda uma referência à actividade(interface)
    }
    else{
        throw new ClassCastException(activity.toString()
                  + " A actividade deve implementar a interface OnOkButtonListener");
    }

    // No onAttach é o local mais seguro para se obter um Context
    context = activity; //Guarda context.

    super.onAttach(activity);
}  

At this point we have everything we need to notify Activity .

Only need to make notification when button is clicked :

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    rootview = inflater.inflate(R.layout.fragment_editar, container, false);

    editar = (EditText) rootview.findViewById(R.id.editar); 
    okBotao = (Button) rootview.findViewById(R.id.ok);

    okBotao.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) { 
            mCallback.onOkButtonClick(editar.getText().toString());
        } 
     }); 
     return rootview;
}  

Note: I changed the line okBotao = (Button) getActivity().findViewById(R.id.ok);
for okBotao = (Button) rootview.findViewById(R.id.ok);
because the answer only makes sense if the button is in Fragment Edit , which is where it should actually be.

The Home Fragment should have a public method to change your TextView:

public void setTextViewText(String text){

    textView.setText(text);
}

On the Activity side we have to implement the interface , declaring the method that will be called by Fragment . As the Activity has a reference to the Fragment Home is just to use it to call your method setTextViewText() :

public static class MainActivity extends Activity implements Editar.OnOkButtonListener{
    ...

    public void onOkButtonClick(string texto){

        //Código para actualizar o Fragment Inicio
        // Ou outra coisa qualquer
        fragmentInicio.setTextViewText(texto);
    }

    ......
}
    
14.04.2015 / 23:34