Calling a method of the class of the Fragment itself

Asked

Viewed 417 times

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 cannot select in onclick the save functionUsuario that is in the class of that fragment, only the functions that are in the parent Activity.

That 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 class itself and not in the main Activity.

thank you.

1 answer

2


1) Remove this line from XML:

android:onClick="salvarUsuario"

2) Inside Oncreateview() of Fragment put this code before 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 save function can be changed to (remove parameters):

public void salvarUsuario(){
    ...
}

Browser other questions tagged

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