Take data from 3 Ragments

Asked

Viewed 791 times

1

Good afternoon, I am developing an android application and in it I have an Activity with 3 Fragments(tabs), where each one contains a part of a form and in the last I have a save button. My difficulty is in how to get the data from the 3 Fragments the moment I click the save button. I read in some places to create a class "transport" to get this data but could not understand very well.

  • One solution is each of the Fragments have a method that returns the form data referring to each of them. These methods will be called in the Activity to build the complete form. The "save" button must be in the Activity.

1 answer

0


The communication between Fragments and the Activity which makes use of them can be made through Interfaces.

Each Fragment of your screen should declare a interface with one or more communication methods, which will be responsible for updating the data in the class implementing such interface (in this case, this class would be Activity itself).

Let’s go to an example. First let’s see the Fragment declaring the communication interface:

public class ExemploFragment extends Fragment {

    // declaração da interface de comunicação
    public interface InterfaceComunicao {

        // aqui, um ou mais métodos de comunicação
        void setIdade(int idade); // por exemplo, este método retorna a idade inserida no fragment
    }

    /* variável que representa quem vai receber a atualização dos dados, 
       no caso a activity principal, que vai implementar a interface de comunicação */
    private InterfaceComunicao listener; 

    @Override
    public void onAttach(Activity activity) {

        /* 
            onAttach faz parte do ciclo de vida do fragment, é executado
                quando o fragment é associado à activity
        */

        super.onAttach(activity);

        if (activity instanceof InterfaceComunicao) {
            listener = (InterfaceComunicao) activity;
        } else {
            throw new RuntimeException("Activity deve implementar ExemploFragment.InterfaceComunicao");
        }
    }

    // um evento qualquer disparado pelo usuário, por exemplo um click de botão
    public void onClickBotaoQualquer() {

        /* 
            - chama o método de comunicação para atualizar o valor que o usuário informou na tela
            - neste ponto, ler o valor de uma view, por exemplo TextView na tela
            - para o exemplo configuramos direto o valor 15
        */
        listener.setIdade(15);

    }

}

To Activity where the Fragment is associated should implement the interface of communication declared in Fragment, in the case Interfacecomunicao, and their respective methods.

public class ExemploActivity extends Activity implements ExemploFragment.InterfaceComunicao {

    .
    .
    .

    // este é o método de comunicação declarado na interface
    // quando o fragment chamar listener.setIdade(15); este é o método que será executado
    @Override
    public setIdade(int idade) {
        /*
            neste ponto, recupera o valor recebido do fragment e 
            implementa o código que desejar
        */ 
    }

    .
    .
    .
}

This approach ensures the independence of Fragment in relation to Activity principal, that is to say decoupling.

This way you can use your Fragment at any other point in its application, it is sufficient that the Activity you want to use it implement the interface communication.

To learn more: https://developer.android.com/guide/components/fragments.html

  • Hello good afternoon, gentlemen I have a problem identico where I need to get the data of three Tabs , where are Fragment with fields of registration this approach to use interface (is in the documentation of Fragments) more in my view is not very good, when the interface method would be fired? have to take into account the behavior of viewPager the ideal would be for the user to navigate to the other tab, I have tried in Activity using viewPager Adapter and arrive at the view of the most unsuccessful Fragment.

Browser other questions tagged

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