<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zachery Osborn on Medium]]></title>
        <description><![CDATA[Stories by Zachery Osborn on Medium]]></description>
        <link>https://medium.com/@zackcosborn?source=rss-57b346b5efed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S3oBw_opgDn-ff1EtdCqSQ.jpeg</url>
            <title>Stories by Zachery Osborn on Medium</title>
            <link>https://medium.com/@zackcosborn?source=rss-57b346b5efed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:14:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zackcosborn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Display Objects of Different Types in a RecyclerView]]></title>
            <link>https://medium.com/@zackcosborn/display-objects-of-different-types-in-a-recyclerview-8b7d8e3968aa?source=rss-57b346b5efed------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b7d8e3968aa</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Zachery Osborn]]></dc:creator>
            <pubDate>Sat, 22 Sep 2018 10:49:19 GMT</pubDate>
            <atom:updated>2018-09-24T23:40:08.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZMMQtP4tuS9PCVqP5MhgQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/tofagMI_UCM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jan Mellström</a> on <a href="https://unsplash.com/search/photos/stacks-of-books%2C-newspapers%2C-magazines?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>So, you may be trying to set up a RecyclerView that has different ViewHolders. For instance, a Post object that could have a picture or might be just text with different ViewHolders for each case.</p><p>While the code in the guide covers that scenario, we are going to take it a step further and also tackle a slightly different problem. Our goal is to add objects of different types<em> </em>to a single RecyclerView in a simple to implement and easy to manage way.</p><p><strong>The Problem:</strong></p><p>We have three objects: Book, Magazine, and Newspaper. We want to display them in one feed by hooking up a single List to a RecyclerView.Adapter. We also want each object type to look different in the RecyclerView.</p><p><strong>What We’ll Need:</strong></p><ul><li>An interface that Book, Magazine, and Newspaper will implement</li><li>A RecyclerView.Adapter with a List of interfaces that can be cast into different types</li><li>A ViewHolder and layout for each object type</li></ul><h4><strong>The Interface</strong></h4><p>Let’s start by creating a Literature interface that all our objects will implement. In the interface we will add a getType() method and some constants that represent the different types. i.e. TYPE_MAGAZINE.</p><pre>public interface Literature {<br>    int <em>TYPE_BOOK </em>= 101;<br>    int <em>TYPE_MAGAZINE </em>= 102;<br>    int <em>TYPE_NEWSPAPER </em>= 103;<br><br>    int getType();<br>}</pre><p>Now, in each of our objects, let’s implement the Literature interface, override the getType() method, and return the correct type for that object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ecbe0380234a083233188f45243797a/href">https://medium.com/media/0ecbe0380234a083233188f45243797a/href</a></iframe><h4><strong>The RecyclerView.Adapter</strong></h4><p>First, let’s add our List of Literatures as a member variable in the Adapter.</p><pre>public class LiteratureAdapter extends RecyclerView.Adapter {<br>    private List&lt;Literature&gt; mLiteratureList;<br>}</pre><p>We will also need three ViewHolders as inner classes in the Adapter. One for each object type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95e50448e19e6fccaa9263578adee922/href">https://medium.com/media/95e50448e19e6fccaa9263578adee922/href</a></iframe><p>We’ll need to override four methods in the RecyclerView.Adapter. The first of which is getItemViewType(). This will look at an item in mLiteratureList and determine if it’s a Book, Magazine, or Newspaper then pass that result to onCreateViewHolder() (which we will implement next).</p><pre>@Override<br>public int getItemViewType(int position) {<br>    return mLiteratureList.get(position).getType();<br>}</pre><p>In onCreateViewHolder() we’ll create a new ViewHolder depending on the type sent from getItemViewType(). <em>Note: In most use cases, you will also have to create a separate layout resource for each </em><em>ViewHolder .</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/572844d0a18dd6623d2e744cb87800aa/href">https://medium.com/media/572844d0a18dd6623d2e744cb87800aa/href</a></iframe><p>In onBindViewHolder() call getItemViewType() manually. Depending on the type that it returns, cast the generic ViewHolder parameter to the appropriate type and call its bindView() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa4e1a9b059d9d582770f5304d916eba/href">https://medium.com/media/fa4e1a9b059d9d582770f5304d916eba/href</a></iframe><p>The code in getItemCount() is going to look the same as in your standard RecyclerView.Adapter.</p><pre>@Override<br>public int getItemCount() {<br>    if (mLiteratureList == null) {<br>        return 0;<br>    } else {<br>        return mLiteratureList.size();<br>    }<br>}</pre><h4><strong>Setting the data</strong></h4><p>The following setter is possible, but<em> </em><strong><em>NOT</em></strong> recommended.</p><pre>public void setLiteratureList(List&lt;Literature&gt; literatureList) {<br>    mLiteratureList = literatureList;<br>    notifyDataSetChanged();<br>}</pre><p>The problem with this approach is either:</p><p>a. In other parts of your app you will have to deal with Literature objects. Which means you will constantly have to check the type and cast them appropriately to get at the data and methods.</p><p>or</p><p>b. You will need to cast your List to a List&lt;Literature&gt; before you can use the setter.</p><p>Another option is to accept any class that implements our Literature interface, then replace the contents of mLiteratureList.</p><pre>public void setLiteratureList(List&lt;? extends Literature&gt; literatureList) {<br>    if (mLiteratureList == null){<br>        mLiteratureList = new ArrayList&lt;&gt;();<br>    }<br>    mLiteratureList.clear();<br>    mLiteratureList.addAll(literatureList);<br>    notifyDataSetChanged();<br>}</pre><p>By following this method, you are able to use a List of Books, Magazines, or Newspapers as the parameter.</p><p>And that’s going to do it. Enjoy your new RecyclerView.Adapter and don’t hesitate to reach out if you have any questions.</p><p>Check out the full RecyclerView.Adapter code <a href="https://gist.github.com/keinix/46848bd52117f533c26b20300ba6abda">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b7d8e3968aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by Step: RecyclerView Swipe to Delete and Undo]]></title>
            <link>https://medium.com/@zackcosborn/step-by-step-recyclerview-swipe-to-delete-and-undo-7bbae1fce27e?source=rss-57b346b5efed------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bbae1fce27e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[gesture-recognition]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Zachery Osborn]]></dc:creator>
            <pubDate>Wed, 12 Sep 2018 14:57:48 GMT</pubDate>
            <atom:updated>2018-09-14T10:25:25.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFp4VmDb0OTebB-6I5VSOw.jpeg" /><figcaption>photo by Magda Ehlers</figcaption></figure><p>Swipe to delete is a prevailing paradigm users are accustomed to on mobile platforms. Adding this functionally is a good way to get your app in line with modern design practices. While there are many libraries that will accomplish this for us, subsequently adding extra bulk to our code, implementing it ourselves is not that complicated. So, let’s get started.</p><p>To implement swipe to delete and undo in our RecyclerView we are going to need 3 key components:</p><ol><li>ItemTouchHelper: This attaches to the RecyclerView and watches for swipes.</li><li>ItemTouchHelper.SimpleCallback: This is passed into ItemTouchHelper’s constructor and contains the code that will run once the item is swiped.</li><li>Snackbar: This is triggered once an item is deleted and gives the user the option to undo the delete.</li></ol><h4><strong>Step 1: ItemTouchHelper.SimpleCallback</strong></h4><p>First, let’s create a new class that extends ItemTouchHelper.SimpleCallback and write the constructor.</p><pre>public class SwipeToDeleteCallback extends ItemTouchHelper.SimpleCallback {</pre><pre>    private MyAdapter mAdapter;</pre><pre>    public SwipeToDeleteCallback(MyAdapter adapter) {<br>        super(0,ItemTouchHelper.<em>LEFT </em>| ItemTouchHelper.<em>RIGHT</em>);<br>        mAdapter = adapter;<br>}</pre><p>The fist parameter in super adds support for dragging the RecyclerView item up or down. We don’t care about that hence the 0. The second parameter tells the ItemTouchHelper (that we will attach to the RecyclerView later) to pass our SimpleCallback information about left and right swipes. The constructor takes a reference to our adapter which we will use to call the deleteItem() function.</p><p>Next, we need to override onSwiped(). This is called when an item is swiped off the screen. You also need to override onMove() , but you can leave it as is.</p><pre>@Override<br>public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {<br>    int position = viewHolder.getAdapterPosition();<br>    mAdapter.deleteItem(position);<br>}</pre><p><em>The </em><em>deleteItem() method does not exist yet but we’ll implement it later in the adapter.</em></p><p>That takes care of the core logic in the SimpleCallback, but we can make it look a little nicer.</p><p><strong><em>Optional Step: Adding the background and Icon</em></strong></p><p>To add our icon and background we just need to override onChildDraw(). This will draw our icon and background in the correct position as our RecyclerView item is swiped across the screen.</p><p>Since onChildDraw() is called multiple times per second, let’s try to keep the code as sparse as possible by adding the icon and background as member variables.</p><pre>private Drawable icon;<br>private final ColorDrawable background;<br><br><br>public SwipeToDeleteCallback(TasksAdapter adapter) {<br>    super(0,ItemTouchHelper.<em>LEFT </em>| ItemTouchHelper.<em>RIGHT</em>);<br>    mAdapter = adapter;<br>    icon = ContextCompat.<em>getDrawable</em>(mAdapter.getContext(),<br>            R.drawable.<em>ic_delete_white_36</em>);<br>    background = new ColorDrawable(Color.<em>RED</em>);<br>}</pre><p>Next, in onChildDraw() we need a reference to our ItemView which will be used to calculate the bounds for both the icon and background.</p><pre>@Override<br>public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {<br>    super.onChildDraw(c, recyclerView, viewHolder, dX,<br>            dY, actionState, isCurrentlyActive);<br>    View itemView = viewHolder.itemView;<br>    int backgroundCornerOffset = 20;<br>}</pre><p>backgroundCornerOffset<em> is used to push the background behind the edge of the parent view so that it appears underneath the rounded corners (as seen in the .gif below). The larger the corner radius of your view, the larger </em>backgroundCornerOffset<em> should be.</em></p><p>Now, we add an if statement that covers the left, right, and no swipe cases. Then, set the bounds for our background in each case respectively and draw it onto the canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2efb10350ba863d7ccc79499949cc6cc/href">https://medium.com/media/2efb10350ba863d7ccc79499949cc6cc/href</a></iframe><p>To add the icon, define the bounds that are consistent across all swipe cases outside the if statement. Then, set the bounds for each case and draw it onto the canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0371f5bd88746beb33324c96a8ba1afd/href">https://medium.com/media/0371f5bd88746beb33324c96a8ba1afd/href</a></iframe><p>Alright, that does it for the ItemTouchHelper.SimpleCallback. Checkout the complete code <a href="https://gist.github.com/keinix/b1aa2417dbea9311a1207eddf8b9d47b">here</a>.</p><h4><strong>Step 2: Attach ItemTouchHelper to the Recyclerview</strong></h4><p>In your Activity or Fragment create a new ItemTouchHelper using our SwipeToDeleteCallback and attach it to the RecyclerView.</p><pre>private void setUpRecyclerView() {<br>    recyclerView.setAdapter(mAdapter);<br>    recyclerView.setLayoutManager(new LinearLayoutManager(this));<br>    ItemTouchHelper itemTouchHelper = new <br>            ItemTouchHelper(new SwipeToDeleteCallback(mAdapter));<br>    itemTouchHelper.attachToRecyclerView(recyclerView);<br>}</pre><h4><strong>Step 3: Deleting the item</strong></h4><p>In the adapter, we need to implement the deleteItem() method we called in SwipeToDeleteCallback earlier. In this method we will first save the removed item into a member variable to be used in case the user wants to undo the delete. We’ll also add a method call to show a Snackbar that we will implement in the next step. Finally, remove the item from our list and update the adapter.</p><pre>public void deleteItem(int position) {<br>    mRecentlyDeletedItem = mListItems.get(position);<br>    mRecentlyDeletedItemPosition = position;<br>    mListItems.remove(position);<br>    notifyItemRemoved(position);<br>    showUndoSnackbar();<br>}</pre><h4><strong>Step 4: Undo Snackbar</strong></h4><p>Once an item is deleted our undo Snackbar should appear. We want the Snackbar’s action to add the recently removed item back to the list and update the adapter.</p><pre>private void showUndoSnackbar() {<br>    View view = mActivity.findViewById(R.id.<em>coordinator_layout</em>);<br>    Snackbar snackbar = Snackbar.<em>make</em>(view, R.string.<em>snack_bar_text</em>,<br>            Snackbar.<em>LENGTH_LONG</em>);<br>    snackbar.setAction(R.string.<em>snack_bar_undo</em>, v -&gt; undoDelete());<br>    snackbar.show();<br>}<br><br>private void undoDelete() {<br>    mListItems.add(mRecentlyDeletedItemPosition,<br>            mRecentlyDeletedItem);<br>    notifyItemInserted(mRecentlyDeletedItemPosition);<br>}</pre><p>And… We’ve done it. Feel free to reach out if you have any questions. Happy coding.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYlvV4IXp8M39I8nCMk%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYlvV4IXp8M39I8nCMk%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYlvV4IXp8M39I8nCMk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="773" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4eccc559e72a113f029db8c8f1daf3/href">https://medium.com/media/ce4eccc559e72a113f029db8c8f1daf3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bbae1fce27e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>