Take data from 2 Ragments by clicking an Action Button (Toolbar)

Asked

Viewed 164 times

1

Come on!

I was looking on the internet about how I could get the values of Edittext of 2 Fragments by clicking on a Action Button of Toolbar, but I didn’t find anything related.

What I found, was passing the data of Fragment to the Activity through the click of a Button in the Fragment.

I have a project that has a Activity Main and by clicking on Menu Drawer she opens a Fragment (Editfragment), so that the user can edit his Profile, change the photo, personal changes and password... This Fragment has a Tablayout with Viewpager with 2 Fragments, where I separate personal changes and password exchange.

The Action Button only appears in the Toolbar when I open that Fragment, he is called in the Fragment and not in the Activity.

How I could get the data from Photo (Editfragment), Personal Data (Editgeraisfragment) and Password (Editsenfragment) by clicking on the Action Button?

Follow the code below:

Editfragment.class

public class EditFragment extends Fragment {

private TabLayout tabLayout;
private ViewPager viewPager;
private ImageView profileImage, addPhoto;
private RelativeLayout relativeEdit;
public static String photoImage, urlImageProfile;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_edit, container, false);
    setHasOptionsMenu(true);

    viewPager = (ViewPager) view.findViewById(R.id.vp_editperfil);
    viewPager.setAdapter(new EditAdapter(getChildFragmentManager(), getActivity()));

    tabLayout = (TabLayout) view.findViewById(R.id.tabs_editperfil);
    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.grey));
    tabLayout.setTabTextColors(getResources().getColor(R.color.grey), getResources().getColor(R.color.colorPrimary));
    tabLayout.setupWithViewPager(viewPager);

    relativeEdit = (RelativeLayout) view.findViewById(R.id.relativeEdit);

    profileImage = (ImageView) view.findViewById(R.id.profile_image);
    addPhoto = (ImageView) view.findViewById(R.id.add_photo);

    photoImage = PrefsUsuario.getPhoto(getActivity());
    urlImageProfile = Funcoes.BuscarUriPhoto(photoImage);

    Picasso.with(getActivity()).load(urlImageProfile).placeholder(R.drawable.imagem_semfoto).into(profileImage);
    Picasso.with(getActivity()).load(R.drawable.icon_add).placeholder(R.drawable.imagem_semfoto).into(addPhoto);

    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_editperfil, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_send:
            return true;
        default:
            return super.onOptionsItemSelected(item);

    }
}
}

Editgeraisfragment.class

public class EditGeraisFragment extends Fragment {

private EditText textNome, textCPF, textEmail, textTelefone;
private Button botaoEnviarGerais;
private ScrollView scrollViewEditGerais;
private static final String URLEnviarGerais = "http://www.caixinhadosmotoristas.com.br/validacao.php?acao=atualizar-gerais";
private RequestQueue requestQueue;
private StringRequest request;
private int idcliente;

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

    textNome = (EditText) view.findViewById(R.id.textNome);
    textCPF = (EditText) view.findViewById(R.id.textCPF);
    textEmail = (EditText) view.findViewById(R.id.textEmail);
    textTelefone = (EditText) view.findViewById(R.id.textTelefone);

    textNome.setText(PrefsUsuario.getNome(getActivity()));
    textCPF.setText(PrefsUsuario.getCpf(getActivity()));
    textCPF.setEnabled(false);
    textEmail.setText(PrefsUsuario.getEmail(getActivity()));
    textTelefone.setText(PrefsUsuario.getTelefone(getActivity()));

    SimpleMaskFormatter mascaraTelefone = new SimpleMaskFormatter("(NN) NNNNN-NNNN");
    MaskTextWatcher maskTelefone = new MaskTextWatcher(textTelefone, mascaraTelefone);
    textTelefone.addTextChangedListener(maskTelefone);

    idcliente = PrefsUsuario.getIdCliente(getActivity());

    return view;
}
}

Editsenhafragment.class

public class EditSenhaFragment extends Fragment {

private EditText textSenhaAtual, textSenhaNova, textConfirmarSenha;
private Button botaoEnviarSenha;
private RelativeLayout relativeEditSenha;
private static final String URLEnviarSenha = "http://www.caixinhadosmotoristas.com.br/validacao.php?acao=atualizar-senha";
private RequestQueue requestQueue;
private StringRequest request;
private int idusuario;

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

    textSenhaAtual = (EditText) view.findViewById(R.id.textSenhaAtual);
    textSenhaNova = (EditText) view.findViewById(R.id.textSenhaNova);
    textConfirmarSenha = (EditText) view.findViewById(R.id.textConfirmarSenha);
    //botaoEnviarSenha = (Button) view.findViewById(R.id.buttonEnviarSenha);
    relativeEditSenha = (RelativeLayout) view.findViewById(R.id.relativeEditSenha);

    textSenhaAtual.setText(PrefsUsuario.getSenha(getActivity()));
    textSenhaAtual.setEnabled(false);

    idusuario = PrefsUsuario.getIdUsuario(getActivity());

    return view;
}
}

Editadapter.class

public class EditAdapter extends FragmentPagerAdapter {
private Context mContext;
private String[] titles = {"PESSOAIS", "SENHA"};

public EditAdapter(FragmentManager fm, Context context) {
    super(fm);
    mContext = context;
}

@Override
public Fragment getItem(int position) {
    Fragment frag = null;

    if(position==0) {
        frag = new EditGeraisFragment();
    } else if(position==1) {
        frag = new EditSenhaFragment();
    }

    Bundle bundle = new Bundle();
    bundle.putInt("position", position);

    frag.setArguments(bundle);

    return frag;
}

@Override
public int getCount() {
    return titles.length;
}

@Override
public CharSequence getPageTitle(int position) {
    return (titles[position]);
}
}

1 answer

3


I believe the simplest way to do that is to warn Activity that the user typed the text and thus send the respective text through a Listener, which was the method you quoted to know, where there is communication fragment-to-activity.

Another option would be, using the same method above, by clicking on Button of Toolbar, send a request to Fragment for it to return the desired data. But, I believe, that the first option be more recommended.

Interface

public interface UserData {
    public void onUserPictureChanged(String path); // É só um exemplo :)
    public void onUserProfileChanged(UserProfile user);
    public void onUserPasswordChanged(String newPassword);
}

Fragment

public class UserProfileSettings extends Fragment {

     private UserData userDataListener;

     @Override
     public void onAttach(Context ctx) {
        super.onAttach(ctx);
        try {
            userDataListener = (UserData) ctx;
        } catch (ClassCastException e) {
            throw new ClassCastException("A activity não implementou a interface UserData corretamente");
        }
     }

     @Override
     public void onViewCreated(View v, Bundle instanceState) {
         super.onViewCreated(v, instanceState)

         inputPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

           }

            @Override
            public void afterTextChanged(Editable s) {
                userDataListener.onUserPasswordChanged(s.toString()) // não se esqueça de verificar se o texto está vazio, ou se é null... etc.
            }
        });
    }
}

Activity

public class MainActivity extends AppCompatActivity implements UserData {

    private String userPwd;

    @Override
    public void onCreate(Bundle instanceState) {
         super.onCreate(instanceState);
         setContentView(R.layout.screen_main);

        // Click Listener hipotético do Botão de voltar da Toolbar....
        example.setOnClickListener {
            if (null != userPwd || userPwd.isNotEmpty()) {
             // faça alguma coisa...
            }
        }
    }

    @Override
    public void OnUserPasswordChange(String newPassword) {
         userPwd = newPassword;
    }
}
  • Just one more question. The Action Button that is in the Toolbar is being called in a Fragment - in this Fragment there are 2 other Fragments inside, where I get the data - and not in Activity, as I do in this case? For in the example you gave me the click on the button is being called in Activity.

  • Strange... because you don’t usually use the Toolbar in a Fragment, but in Activity, because it is she who will control 'everything', regardless of Fragment. But I believe it works anyway, but you will need to implement the interface, just as if it were in Activity.

  • So Toolbar she is in Activity, but the Menu call she is only in Fragment, understand? That’s why I’m asking if Clicklistener has to be in Activity or Fragment?

  • Now that I can understand. Next, make a communication between Factions. Basically, the 2 data entry Ragments will send the data to Editfragment and, in this, you send the data to Activity. That is, the call can be in Fragment itself. If it doesn’t work, call Actionbutton in Activity.

  • 1

    Thanks @itscorey gave it right!

Browser other questions tagged

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