How to pass the Edittext value of a Fragment to the Textview of another Fragment?

Asked

Viewed 1,039 times

4

I have a Fragment that contains an Edittext in which the user will enter his name.

In another Fragment is Textview which will receive the name typed in the previous Fragment.

Fragment Edit (where the user will enter 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;
    }
}

Fragment Start (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; 
    }
}

  • You didn’t make the change to String.valueOf(editar). That looking at the question will think that this is a duplicate of the other and will vote to close.

  • I changed it, but I sent the wrong code. I’ll send the updated one. Sorry.

  • I don’t see how you have Fragment start displayed. onClick creates an instance of it, does the setArguments() but then do nothing else.

  • Can I do this with Return menu? But then I would have to take the rootview Return, it’s not?

  • Or I can use: [Fragmenttransaction transaction = getFragmentManager(). beginTransaction(); transaction.replace(R.id.container, menu); transaction.addToBackStack(null); transaction.commit();] ?

  • It can but only in Activity. I think the solution would be the method onClick call a method of Activity and so on. Who should control the Fragments must be the Activity.

  • Ah, then in case use within onCreat ((Minhaactivity)getActivity()). nameMethod(); ?

  • In the onClick(View v). ((MinhaActivity)getActivity()).nomeDoMétodo(editar.getText().toString());. Check whether getActivity() does not return null, should not but if return tell me.

  • I can’t right now, but later I’ll put an answer to how to do that "correct".

  • Thank you so much for everything. I will try the last change you sent.

  • I have the answer ready, but at the time I was reviewing it I noticed that you are getting a reference to okBotao using getActivity. Is the button in Fragment or is it in Activity? If it is in Activity everything we have said is no longer meaningful.

  • The button is in the Fragment.

Show 7 more comments

1 answer

3


You’re struggling because you’re assigning responsibilities to Fragment Edit that shouldn’t be his.

The control of Fragments associated with a Activity is the responsibility of this.

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

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

How to manage the Fragments is from Activity we have to find a way to notify her.
How to ensure that the Activity treats this notification is to oblige it to implement a interface when you try to associate the Fragment Edit.

In class Edit we declare the interface to be implemented and a field to keep a reference to who to implement it:

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 method onAttach() we check whether the Activity, who is trying to associate the Fragment, implements the interface and we keep your 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);
}  

Right now we have everything we need to notify Activity.

Notification only needs to be made when the 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 on Fragment Edit, which is where you should actually be.

Start Fragment must have a public method to change its Textview:

public void setTextViewText(String text){

    textView.setText(text);
}

On the side of Activity we have to implement the interface, declaring the method to be called by Fragment.
Since Activity has a reference to Fragment Inicio just use it to call its 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);
    }

    ......
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.