RecyclerView onClickListener for activity dialog

0

I have a recycler view, and would like to pass the parameters I get from it to a dialog in the activity edit the values and save again in the database

I have a registered abstract method

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

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

the adapter for that adapter's recycler view.

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: the recycler view already loads all the values, but now I want to receive 1 value based on the click position of the recycler view, pass in the edit dialog and save again. I tried some methods but without result, I also researched a lot, but I did not find anything that solved the doubt.

    
asked by anonymous 08.03.2017 / 19:28

1 answer

0

Interface:

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

Inside the Adapter_Users:

@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;
    }

Na 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 the activity and save it to a database (Creates interface > calls the interface method in the > in activity ... exactly the same as the click of the adapter).

    
08.03.2017 / 21:22