Create a gist now

Instantly share code, notes, and snippets.

package com.andraskindler.playground.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.andraskindler.playground.Item;
import com.andraskindler.playground.R;
import java.util.List;
public class ListAdapter extends BaseAdapter {
final List<Item> items;
public ListAdapter(List<Item> items) {
this.items = items;
}
@Override public int getCount() {
return items.size();
}
@Override public Item getItem(int i) {
return items.get(i);
}
@Override public long getItemId(int i) {
return i;
}
@Override public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_list, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.titleTextView = (TextView) view.findViewById(R.id.tv_title);
viewHolder.bodyTextView = (TextView) view.findViewById(R.id.tv_body);
view.setTag(viewHolder);
}
final Item item = items.get(i);
final ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.titleTextView.setText(item.title);
viewHolder.bodyTextView.setText(item.body);
return view;
}
private static final class ViewHolder {
public TextView titleTextView, bodyTextView;
}
}
package com.andraskindler.playground.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.andraskindler.playground.Item;
import com.andraskindler.playground.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
final List<Item> items;
public RecyclerViewAdapter(List<Item> items) {
this.items = items;
}
@Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_list, null);
return new ViewHolder(view);
}
@Override public void onBindViewHolder(ViewHolder viewHolder, int i) {
final Item item = items.get(i);
viewHolder.titleTextView.setText(item.title);
viewHolder.bodyTextView.setText(item.body);
viewHolder.currentItem = item;
}
@Override public int getItemCount() {
return items.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView, bodyTextView;
public Item currentItem;
public ViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.tv_title);
bodyTextView = (TextView) v.findViewById(R.id.tv_body);
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Toast.makeText(v.getContext(), currentItem.title, Toast.LENGTH_SHORT).show();
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment