Skip to content

Instantly share code, notes, and snippets.

@girish3
Last active May 24, 2020 11:05
Show Gist options
  • Save girish3/8807476c805d0bb16d38 to your computer and use it in GitHub Desktop.
Save girish3/8807476c805d0bb16d38 to your computer and use it in GitHub Desktop.
[[Deprecated] Recycler view] Its too much work when I need a simple list to experiment some stuff in Android. This file to my rescue. #android_snippet #android

Adapter

// Adapter code
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    ArrayList<String> mItems;

    public CustomAdapter(Context context, ArrayList<String> items) {

        String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
                "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
                "Android", "iPhone", "WindowsMobile" };

        mItems = new ArrayList<>(Arrays.asList(values));
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        // create a new view
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(android.R.layout.simple_list_item_1, viewGroup, false);
        CustomViewHolder cvh = new CustomViewHolder(v);
        return cvh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        CustomViewHolder vh = (CustomViewHolder) viewHolder;
        vh.mText.setText(mItems.get(position));
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    @Override
    public int getItemViewType(int position) {
        // Just as an example, return 0 or 2 depending on position
        // Note that unlike in ListView adapters, types don't have to be contiguous
        return 0;
    }
}

ViewHolder code

class CustomViewHolder extends RecyclerView.ViewHolder {

	public TextView mText;

	public CustomViewHolder(View root) {
		super(root);
		mText = (TextView) root.findViewById(android.R.id.text1);
	}
}

Add following in your activity

// add the following in activity
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
CustomAdapter customAdapter = new CustomAdapter(this, null);
mRecyclerView.setAdapter(customAdapter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment