Created
September 14, 2016 05:23
-
-
Save maydin/59c790178e7064ab7e4ed2703a4a51f9 to your computer and use it in GitHub Desktop.
Adapter class with Rx
This file contains 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
public class ApplianceAdapter extends | |
RecyclerView.Adapter<ApplianceAdapter.ViewHolder> { | |
private List<Appliance> applianceList; | |
private Context mContext; | |
public ApplianceAdapter(Context context, List<Appliance> applianceList) { | |
this.applianceList = applianceList; | |
this.mContext = context; | |
} | |
// Easy access to the context object in the recyclerview | |
private Context getContext() { | |
return mContext; | |
} | |
public static class ViewHolder extends RecyclerView.ViewHolder { | |
public TextView nameTextView; | |
// We also create a constructor that accepts the entire item row | |
// and does the view lookups to find each subview | |
public ViewHolder(View itemView) { | |
// Stores the itemView in a public final member variable that can be used | |
// to access the context from any ViewHolder instance. | |
super(itemView); | |
nameTextView = (TextView) itemView.findViewById(R.id.appliance_name_textview); | |
} | |
} | |
@Override | |
public ApplianceAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { | |
Context context = parent.getContext(); | |
LayoutInflater inflater = LayoutInflater.from(context); | |
// Inflate the custom layout | |
View applianceView = inflater.inflate(R.layout.appliance_row_item, parent, false); | |
// Return a new holder instance | |
ViewHolder viewHolder = new ViewHolder(applianceView); | |
return viewHolder; | |
} | |
// Involves populating data into the item through holder | |
@Override | |
public void onBindViewHolder(ApplianceAdapter.ViewHolder viewHolder, int position) { | |
Appliance appliance = applianceList.get(position); | |
TextView textView = viewHolder.nameTextView; | |
textView.setText(appliance.name); | |
} | |
@Override | |
public int getItemCount() { | |
return applianceList.size(); | |
} | |
public void addAppliance(Appliance appliance) | |
{ | |
if(!applianceList.contains(appliance)) | |
{ | |
this.applianceList.add(appliance); | |
notifyItemInserted(applianceList.size()-1); | |
} | |
} | |
public void removeAppliance(Appliance appliance) | |
{ | |
if(applianceList.contains(appliance)) | |
{ | |
final int position = this.applianceList.indexOf(appliance); | |
this.applianceList.remove(appliance); | |
notifyItemRemoved(position); | |
} | |
} | |
public void clearAppliances() | |
{ | |
int size = applianceList.size(); | |
applianceList.clear(); | |
notifyItemRangeRemoved(0,size); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment