I have an ArrayList which provides the data to the RecyclerView, the idea is that when you click on an item it is deleted, I already implement the onClick method and I also have the line of code to delete a data from the arrayList, but I don't know how to do it so that it is updated and the data is seen except the one that was deleted.
This is the main class
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Personas> lista;
TextView texto;
Adaptador adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista = new ArrayList<>();
texto = (TextView)findViewById(R.id.Nombre);
recyclerView = (RecyclerView)findViewById(R.id.Recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
llenarDtos();
adapter= new Adaptador(lista);
recyclerView.setAdapter(adapter);
adapter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lista.remove(recyclerView.getChildAdapterPosition(v));
Toast.makeText(getApplicationContext(),lista.get(recyclerView.getChildAdapterPosition(v)).getNombre(),Toast.LENGTH_SHORT).show();
}
});
}
private void llenarDtos() {
lista.add(new Personas("Pablo","5",R.drawable.fuego));
lista.add(new Personas("Sebastian","7",R.drawable.manzana));
lista.add(new Personas("Juan","9",R.drawable.suplemento));
lista.add(new Personas("Camila","4",R.drawable.manzana));
lista.add(new Personas("Tatiana","2",R.drawable.fuego));
}
}
This is the adapter
public class Adaptador extends RecyclerView.Adapter<Adaptador.ViewHolderPersonas> implements View.OnClickListener {
ArrayList<Personas> lista;
View.OnClickListener listener;
public Adaptador(ArrayList<Personas> lista) {
this.lista = lista;
}
@Override
public ViewHolderPersonas onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);
view.setOnClickListener(this);
return new ViewHolderPersonas(view);
}
@Override
public void onBindViewHolder(ViewHolderPersonas holder, int position) {
holder.nombre.setText(lista.get(position).getNombre());
holder.info.setText(lista.get(position).getInfo());
holder.foto.setImageResource(lista.get(position).getFoto());
}
@Override
public int getItemCount() {
return lista.size();
}
public void setOnClickListener(View.OnClickListener listener)
{
this.listener = listener;
}
@Override
public void onClick(View v) {
if(listener!=null)
{
listener.onClick(v);
}
}
public class ViewHolderPersonas extends RecyclerView.ViewHolder {
TextView nombre;
TextView info;
ImageView foto;
public ViewHolderPersonas(View itemView) {
super(itemView);
nombre= (TextView)itemView.findViewById(R.id.Nombre);
info= (TextView)itemView.findViewById(R.id.Informacion);
foto= (ImageView) itemView.findViewById(R.id.foto);
}
}
}
You just need to notify the adapter that you just removed an element: