Get data from 2 fragments by clicking an Action Button (Toolbar)

1

Come on!

I was searching the internet for how I could get the EditText values of 2 Fragments by clicking an Action Button from the Toolbar , but I did not find anything related.

What I found was passing the Fragment data to Activity by clicking Button on Fragment .

I have a project that has a Activity Main and by clicking the Drawer Menu it opens a Fragment (EditFragment) so that user can edit your Profile, change photo, personal changes and password ... This Fragment has a TabLayout with ViewPager with 2 Fragments , where I separate personal changes and password changes.

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

How could I get EditFragment, Personal Data (EditGenFragment), and Password (EditSenhaFragment) when I clicked the Action Button?

The following is 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]);
}
}
    
asked by anonymous 28.10.2017 / 09:13

1 answer

3

I think the simplest way to do this is to tell Activity that the user typed the text and thus send the 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 to return the desired data. But I think the first choice is best 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;
    }
}
    
28.10.2017 / 15:00