Recyclerview onClickListener for Activity dialog

Asked

Viewed 580 times

0

I have a Recycler view, and would like to pass the parameters I receive from it to a dialog in Activity edit the values and save again in the bank

I have a recorded abstract method

public interface RecyclerViewOnClickListenerHack {
    public void onClickListener(View view, int position);

    public void onLongPressClickListener(View view, int position);
}

the Adapter referring to the Recycler view of that Adapter.

public class Adapter_Usuarios extends  RecyclerView.Adapter<Adapter_Usuarios.MyViewHolder> implements  RecyclerViewOnClickListenerHack {

    private List<Usuarios_Model> user_List;
    private Context c ;
    private LayoutInflater mLayoutInflater;
    RecyclerViewOnClickListenerHack mRecyclerViewOnClickListenerHack;
    private int posicao;

    public Adapter_Usuarios(List<Usuarios_Model> user_List,Context c ){
        this.user_List = user_List;
        this.c = c;
        this.mLayoutInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // onde vai inflar o layout do adapter para o recycler view
        View v = mLayoutInflater.inflate(R.layout.adapter_usuarios, parent , false);
        MyViewHolder mvh = new MyViewHolder(v);
        return mvh;


    }



    @Override
    public void onBindViewHolder(final MyViewHolder holder,final int position) {// seta todos os valores no banco

        holder.txt_id.setText(String.valueOf(user_List.get(position).getId()));
        holder.txt_nome.setText(user_List.get(position).getNome());
        holder.txt_email.setText(user_List.get(position).getEmail());
        holder.txt_usuario.setText(user_List.get(position).getUsuario());
        holder.txt_senha.setText(user_List.get(position).getSenha());
        holder.txt_tipo.setText(user_List.get(position).getTipo_usuario());
        holder.llm1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(c, "OnClick Called at position " + (position+1), Toast.LENGTH_SHORT).show();
            }
        });// fim holder.llm1.setOnClickListener





    }

    @Override
    public int getItemCount() {
        return user_List.size();
    }

    public void setRecyclerViewOnClickListenerHack(RecyclerViewOnClickListenerHack r){
        mRecyclerViewOnClickListenerHack = r;
    }


    public void onClickListener(View view, int position) {
        Log.i("teste", "onClickListener: ");
    }

    @Override
    public void onLongPressClickListener(View view, int position) {
        Log.i("teste","onLongclick");


    }


    public class MyViewHolder extends  RecyclerView.ViewHolder {

        public TextView txt_id;
        public TextView txt_nome;
        public TextView txt_usuario;
        public TextView txt_senha;
        public TextView txt_email;
        public TextView txt_tipo;
        public LinearLayout llm1;



        public  MyViewHolder   (View itemView) {
            super(itemView);


            txt_id = (TextView) itemView.findViewById(R.id.txt_id);
            txt_nome = (TextView) itemView.findViewById(R.id.txt_nome);
            txt_usuario = (TextView) itemView.findViewById(R.id.txt_usuario);
            txt_senha = (TextView) itemView.findViewById(R.id.txt_senha);
            txt_email = (TextView) itemView.findViewById(R.id.txt_email);
            txt_tipo = (TextView) itemView.findViewById(R.id.txt_tipo1);
            llm1 = (LinearLayout) itemView.findViewById(R.id.ll_adicionar);


        }// fim myviewholder interno

    } // fim myviewholder

}// fim class adapter_usuarios

and the page with my dialog

 public class Admin_Usuarios  extends AppCompatActivity implements RecyclerViewOnClickListenerHack {

    List<Usuarios_Model> user_List;
    String tipo;
    String senha;
    String nome;
    String usuario;
    String email;
    String id_tipo;
    Button bt_excluir;
    Button bt_editar;
    Usuarios_Model u;

 boolean confirmacao;
    private static final String PREF_NAME = "Login";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.admin_usuarios);

        bt_excluir = (Button) findViewById(R.id.btexcluir);
        bt_editar = (Button) findViewById(R.id.btalterar);

        mToolbar = (Toolbar) findViewById(R.id.toolbar_admin_usuarios);
        mToolbar.setTitle("Administração de Usuários");
        setSupportActionBar(mToolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_users);
        RecyclerView.LayoutManager layout = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layout); // intanciando o recycler view que será usado, e dizendo o layout que irá utilizar
        // agora a Lista que será carregada no recycler view

        final List<Usuarios_Model> user_List = new DAO_usuario().ListAll();
        if (user_List.size() > 0) {

            recyclerView.setAdapter(new Adapter_Usuarios(user_List, getApplicationContext()));

             u = (Usuarios_Model) getIntent().getSerializableExtra("usuario");


        }// fim if userlist size -> se a lista for maior q 0... carrega os dados....


    }// fim oncreate


    public void ChamarDialog(View view)
    {   confirmacao = true;
        ExibeDialog();

    }




    public void ExibeDialog(){

        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_adicionar_usuario);




        final Button btcriar = (Button) dialog.findViewById(R.id.btcriar);
        final Button cancelar = (Button) dialog.findViewById(R.id.btcancelar);
        final EditText etid = (EditText) dialog.findViewById(R.id.etidd);
        final EditText etnome = (EditText)dialog.findViewById(R.id.etnomed);
        final EditText etusuario = (EditText) dialog.findViewById(R.id.etusuariod);
        final EditText etsenha = (EditText) dialog.findViewById(R.id.etsenhad);
        final EditText etemail = (EditText)dialog.findViewById(R.id.etemaild);
        final Spinner spin1= (Spinner) dialog.findViewById(R.id.sptipo_usuariod);

            // inicio do spinner
        final ArrayAdapter adapter = new ArrayAdapter(this ,android.R.layout.simple_spinner_dropdown_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        List<String> tipos = new ArrayList<String>();
        tipos.add("Administração");
        tipos.add("Comum");
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, tipos);
        ArrayAdapter<String> spinnerArrayAdapter = arrayAdapter;
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spin1.setAdapter(spinnerArrayAdapter);
        spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View v, int posicao, long id) {
                //pega nome pela posição
                tipo = parent.getItemAtPosition(posicao).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // final spinner



        if(confirmacao == true) {
            dialog.setTitle("Adicionar Usuarios");
            btcriar.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    nome = etnome.getText().toString();
                    email = etemail.getText().toString();
                    usuario = etusuario.getText().toString();
                    senha = etsenha.getText().toString();
                    id_tipo = etid.getText().toString();
                    u = new Usuarios_Model();

                    u.setNome(nome);
                    u.setEmail(email);
                    u.setSenha(senha);
                    u.setUsuario(usuario);
                    u.setTipo_usuario(tipo);
                    u.setId(Integer.parseInt(id_tipo));
                    List<Usuarios_Model> ls = new ArrayList<>();
                    ls.add(u);
                    new DAO_usuario().Insert(ls);

                    //finaliza o dialog
                    dialog.dismiss();

                    finish();
                    startActivity(getIntent());


                    Toast.makeText(Admin_Usuarios.this, "Usuario Criado!", Toast.LENGTH_SHORT).show();
                }
            });

        }// se o teste for true crie o usuario

        else// se nao for...
        {   dialog.setTitle("Editar Usuarios");
            btcriar.setText("Editar");



            etid.setText(u.getId());
            etnome.setText(u.getNome());
            etemail.setText(u.getEmail());
            etusuario.setText(u.getUsuario());
            etsenha.setText(u.getSenha());
            spin1.setAdapter(arrayAdapter);



                nome = etnome.getText().toString();
                email = etemail.getText().toString();
                usuario = etusuario.getText().toString();
                senha = etsenha.getText().toString();
                id_tipo = etid.getText().toString();
                u = new Usuarios_Model();

                u.setNome(nome);
                u.setEmail(email);
                u.setSenha(senha);
                u.setUsuario(usuario);
                u.setTipo_usuario(tipo);
                u.setId(Integer.parseInt(id_tipo));
                List<Usuarios_Model> ls = new ArrayList<>();

                ls.add(u);

                new DAO_usuario().Insert(ls);


                dialog.dismiss();

                finish();
                startActivity(getIntent());


                Toast.makeText(Admin_Usuarios.this, "Usuario alterado!", Toast.LENGTH_SHORT).show();






        }// se o teste for false edita
        cancelar.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //finaliza o dialog
                dialog.dismiss();

            }



        }); // fim btcriar set click listener
        dialog.show();


    } // fim exibedialog














    @Override
    public void onClickListener(View view, int position) {

        confirmacao = false;
        Log.i("teste2", "onClickListener: ");

        u = user_List.get(position);

       ExibeDialog();




    }// fim onClickListener








    @Override
    public void onLongPressClickListener(View view, int position) {

    }

        protected void onResume() {
            super.onResume();

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                mToolbar.setBackgroundResource(R.drawable.toolbar_rounded_corners);
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_generic, menu);
            return true;
        }
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();

            if(id == android.R.id.home){
                finish();
            }

            return true;
        }

}

Note: Recycler view already loads all values, but now I want to receive 1 value based on the position of the Recycler view click, pass the edit dialog and save again. tried some methods but without result, I also researched enough but I did not find anything that solved the doubt

  • On the interface, instead of passing the "View, int position" parameters, you can return only the Usuarios_model object (since onBindViewHolder returns the position) based on the position of the user_List variable. In activty, Voce receives this object from the user and already instantiates a dialog passing the whole object to that dialog. When saving, don’t forget to have another callback to update the list with the new value that has just been updated. Remembering that the llm1 object should call the onClick method of the interface. .

  • In short: In Activity, you create Adapter. You pass an interface object inside Adapter. In the user click (which is in onBindViewHolder), you call interface.onClick(user) passing the clicked user based on the position of the list that is in Adapter. This user will "return" to Activity. So, from there, you already create the dialog by passing the user as parameter and valuing the fields. In the act of saving, create another callback for Activity to update Adapter data.

  • let’s see if you mean it.No need to return the view and position so I can put a User object model, put the onclick in the layout returning to the layout (a layout method) and not to the dialog directly...

  • if you can show me somehow because I’m still confused, I tried to do seeing several codes and unfortunately just confused me more what is missing is to make this call again the method for editing getting the values changing and saving is done

1 answer

0


Interface:

public interface RecyclerViewOnClickListenerHack {
    public void onClickListener(Usuarios_Model usuario); // obj usuario
}

Inside the User Adapter:

@Override
    public void onBindViewHolder(final MyViewHolder holder,final int position) {

        holder.llm1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                mRecyclerViewOnClickListenerHack.onClick(user_List.get(position)); 
                // manda o user para a interface "devolver" para a activity
            }
        });
    }

public void setRecyclerViewOnClickListenerHack(RecyclerViewOnClickListenerHack response){
        mRecyclerViewOnClickListenerHack = response;
    }

In Activity:

meuAdapter.setRecyclerViewOnClickListenerHack(new RecyclerViewOnClickListenerHack (){
   @Override
   public void onClickListener(Usuarios_Model usuario){

    // o click no adapter vai evocar esse método que está dentro da activity, "devolvendo" o usuário no parametro logo acima
   // chama o diálogo e passa esse usuário para o diálogo...

   meuDialogo.setUser(usuario);
   meuDialogo.show();
   }

});

After sending the user to the dialog and editing, just use the same technique to send it "back" to Activity and save it in a database (Creates interface>calls the interface method in the dialog>program the update in Activity...exactly the same as the Adapter click).

  • thanks Mr_anderson. clarified a lot!!! was wrong even when calling on Adapter

  • it might work if it worked, please.

Browser other questions tagged

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