Call a class method of the fragment itself

0

Good afternoon, I have a fragment that has the following XML

  <Button
    android:id="@+id/salvar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/gradiente_azul_semconor"
    android:text="Salvar"
    android:textColor="@color/cinza"
    android:onClick="salvarUsuario"
    android:layout_below="@+id/relativeLayout" />

But I can not select onclick the saveUsuario function that is in the class of this fragment, just the functions that are in the parent activity.

This would be the function:

  public void salvarUsuario(View view){

        EditText nomeEt = (EditText) getActivity().findViewById(nome);
        EditText emailEt = (EditText) getActivity().findViewById(email);
        EditText npEt = (EditText) getActivity().findViewById(np);
        Spinner tipoFuncSp = (Spinner) getActivity().findViewById(tipoFunc);
        Button salvarBt = (Button) getActivity().findViewById(salvar);

        usuario.setNome(nomeEt.getText().toString());
        usuario.setEmail(emailEt.getText().toString());
        usuario.setTipoFunc(tipoFuncSp.toString());
        usuario.setNp(npEt.getText().toString());

        db_funcao bd = new db_funcao(getContext());
        bd.inserir(usuario);

        Toast.makeText(getActivity(), "Usuário inserido com sucesso!", Toast.LENGTH_SHORT).show();
    }

How do I call a function that is in the fragment's own class and not in the main activity.

Thank you.

    
asked by anonymous 20.06.2017 / 19:09

1 answer

2

1) Remove this line from XML:

android:onClick="salvarUsuario"

2) Within Fragment's OnCreateView () put this code before the return:

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

    ...

    Button salvarBt = rootView.findViewById(R.id.salvar);
    salvarBt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            salvarUsuario();
        }
    });

    return rootView;
}

3) Your userSave function can be changed to (remove parameters):

public void salvarUsuario(){
    ...
}
    
20.06.2017 / 20:16