Created
September 21, 2022 13:15
-
-
Save anta40/4d8d328525f21a3249dd55e7654f378b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.anta40.app.countrycruddemo; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Button; | |
import android.widget.TextView; | |
import androidx.annotation.NonNull; | |
import androidx.recyclerview.widget.RecyclerView; | |
import java.util.List; | |
public class CountryAdapter extends RecyclerView.Adapter<CountryAdapter.ViewHolder> { | |
private List<Country> data; | |
class ViewHolder extends RecyclerView.ViewHolder { | |
public TextView tvId; | |
public TextView tvName; | |
public TextView tvPopulation; | |
public Button btnEdit; | |
public Button btnDelete; | |
public ViewHolder(@NonNull View itemView) { | |
super(itemView); | |
tvId = itemView.findViewById(R.id.tvCountryID); | |
tvName = itemView.findViewById(R.id.tvCountryName); | |
tvPopulation = itemView.findViewById(R.id.tvCountryPopulation); | |
btnEdit = itemView.findViewById(R.id.btnEdit); | |
btnDelete = itemView.findViewById(R.id.btnDelete); | |
} | |
} | |
public CountryAdapter(List<Country> data){ | |
this.data = data; | |
} | |
public void updateAndRefreshData(List<Country> newData){ | |
data.clear(); | |
data.addAll(newData); | |
notifyDataSetChanged(); | |
} | |
@NonNull | |
@Override | |
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { | |
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); | |
View theView = layoutInflater.inflate(R.layout.country_item, parent, false); | |
ViewHolder viewHolder = new ViewHolder(theView); | |
return viewHolder; | |
} | |
@Override | |
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { | |
Country selectedCountry = data.get(position); | |
holder.tvId.setText(String.valueOf(selectedCountry.getId())); | |
holder.tvName.setText(selectedCountry.getName()); | |
holder.tvPopulation.setText(String.valueOf(selectedCountry.getPopulation())); | |
} | |
@Override | |
public int getItemCount() { | |
if (data == null) return 0; | |
else return data.size(); | |
} | |
public void removeItem(int position){ | |
data.remove(position); | |
notifyItemRemoved(position); | |
notifyItemRangeChanged(position, getItemCount() - position); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment