<?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 Vitaly Vivchar on Medium]]></title>
        <description><![CDATA[Stories by Vitaly Vivchar on Medium]]></description>
        <link>https://medium.com/@vivchar?source=rss-2a5602aa78ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wnEajMD7CiUx5zcclIUDuA.jpeg</url>
            <title>Stories by Vitaly Vivchar on Medium</title>
            <link>https://medium.com/@vivchar?source=rss-2a5602aa78ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:24:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vivchar/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[Тренировки на самоизоляции c Fitmer]]></title>
            <link>https://medium.com/@vivchar/%D1%82%D1%80%D0%B5%D0%BD%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B8-%D0%BD%D0%B0-%D1%81%D0%B0%D0%BC%D0%BE%D0%B8%D0%B7%D0%BE%D0%BB%D1%8F%D1%86%D0%B8%D0%B8-c-fitmer-b947734e1e50?source=rss-2a5602aa78ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b947734e1e50</guid>
            <category><![CDATA[tabata]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[workout]]></category>
            <dc:creator><![CDATA[Vitaly Vivchar]]></dc:creator>
            <pubDate>Wed, 06 May 2020 14:49:15 GMT</pubDate>
            <atom:updated>2020-05-06T14:49:15.180Z</atom:updated>
            <content:encoded><![CDATA[<p>Сегодня, в связи с пандемией коронавируса, мы вынуждены соблюдать режим самоизоляции. Многие уже изрядно заскучали, а я считаю это очень полезным временем для саморазвития. На протяжении нескольких недель я вел работу от 13 до 16 часов в день и очень надеюсь, что не зря. Результатом этого стало созданное мною приложение для ваших тренировок.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGbuDijzK8xZwgKOAF4_EQ.png" /></figure><h3>FITMER</h3><p>Это интервальный фитнес таймер, который способен улучшить качество тренировок. Так как на данный момент все спортивные учреждения не функционируют, а в домашних условиях самостоятельно заниматься может далеко не каждый, то это приложение послужит отличным инструментом для систематизации любых домашних тренировок(йога, пилатес, стретчинг, силовые, кроссфит, кардио, воркаут, аэробика и другие интервальные тренировки).</p><h3>Первый запуск</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*trfotHEvvA8UMK0d.jpg" /></figure><p>При первом запуске, вы увидите минималистичный дизайн в темных тонах, я решил сосредоточить ваше внимание на важных вещах, которые я выделил ярко-зеленым цветом.</p><p>На стартовой странице подготовлена демонстрационная тренировка, которую вы сразу же можете запустить простым нажатием и проверить как она работает.</p><p>Конечно, у вас появится потребность сформировать собственную тренировку, для этого вам нужно нажать на плюсик.</p><p>В случае необходимости вы можете отредактировать уже существующие тренировки. Например, спустя время, вы захотите их модернизировать — нажмите на карандашик в любой из тренировок.</p><h3>Редактирование</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*NDHP3l3c6akV9XTi.jpg" /></figure><p>При нажатии на плюсик или карандашик вы попадете на страницу конфигурирования тренировки.</p><p>На что стоит обратить внимание? Любая тренировка может состоять из трех видов «Секций/блок» — пока лучше название я не придумал, поэтому давайте использовать именно такой термин :) Каждая секция выделена на рисунке темным фоном.</p><p><strong>Секция «Отдых»</strong></p><p>Это самый простой вид, который используются для разделения двух других видов секций перерывами, для того чтобы вы могли перевести дыхание. В этой секции доступно к изменению лишь количество секунд вашего отдыха.</p><p><strong>Секция «Упражнение»</strong></p><p>Это традиционный вид упражнения в любой тренировке — комбинация конкретного упражнения и отдыха, которое требуется повторить определенное количество раз, иными словами — количество подходов. Здесь подлежит изменению обьем заданной работы — время под нагрузкой, а так же время отдыха после нагрузки и количество подходов/циклов этой секции.</p><p>Так же хочу заметить что в этой секции последний отдых в последнем цикле/подходе будет автоматически пропускаться и за ним будет находиться следующая секция. Это необходимо для возможности явного добавления отдыхов между cекциями не учитывая имеющийся отдых в последнем упражнении. Cобственно, стандартная тренировка проходит именно таким же образом, отдыхи между подходами и отдыхи между упражениями никогда не суммируются — после заключительного подхода всегда идет отдых перед следующим упражнением.</p><p><strong>Секция «Сет»</strong></p><p>Это самый сложный вид секций, здесь вы можете комбинировать любые последовательности отдыхов, упражнений исходя из ваших целей. Здесь представлена возможность добавления двух и более последовательных упражнения, включая отдых после — это интерпретация классических сетов и супер-сетов в тренировках.</p><p><em>Примечание:</em> не стоит добавлять несколько отдыхов подряд — таймер будет ругать халявщиков и не даст сохранить тренировку ;)</p><h3>Запуск тренировки</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*uru8o0zXE2XApsLK.jpg" /></figure><p>Для запуска просто нажмите на стартовой странице на любую тренировку. Таймер загрузит ее и будет готов, по вашей команде, начать отсчитывать время нулевого блока, т.е. время для подготовки перед вашим первым блоком, за это время необходимо успеть подготовиться к упражнению(подойти к снаряду, занять необходимое положение).</p><p>В центре экрана вы увидите обратный отсчет текущего состояния вашей тренировки — это может быть отдых, либо упражнение. Вокруг этой цифры вы видите два прогресса — внутренний это прогресс текущего состояния, а внешний — всей тренировки, так же весь обратный отсчет всей тренировки виден под основным значением таймера.</p><p>В нижней части экрана вы видите те самые «Секции», которые расположились вертикально и выделены темным фоном, в заголовке вы видите номер секции и количество оставшегося времени в ней, внутри самой секции вы видите все ваши последовательности которые вы создали — комбинации отдыхов и упражнений. Здесь все ваши секции выглядят одинаково — нет смысла их различать, так как любой сет или тренировка — это просто набор последовательности отдыха и работы.</p><p>При необходимости вы можете проматывать ваши тренировки и возвращаться к предыдущим, для просмотра имеющихся — поскролльте, для запуска, приостановки и переключения — воспользуйтесь специальной панелью управления над блоком.</p><h3>Звуковое сопровождение</h3><p>В начале каждой «работы» вы услышите «свисток» — команда старт — пора пахать!</p><p>Как только ваша работа будет подходить к концу — таймер начнет подавать сигнал «гудок» за три секунды до финиша текущего состояния чтобы вы морально успели подготовиться :)</p><p>В конце работы вы услышите «гонг» — значит пора отдохнуть. В конце отдыха таймер так же начнет отсчитывать три секунды, чтобы вы успели занять позицию заранее.</p><p>Когда вся тренировка закончена — вы услышите «тройной гонг» — вы молодец!</p><h3>Заключение</h3><p>Я бы хотел чтобы данное приложение было вашим надежным инструментом для домашних тренировок, поэтому я открыт для всех видов отзывов. Давайте сделаем его действительно удобным и полезным вместе ;)</p><p>Данное приложение уже доступно на всех платформах. Попробовать приложение вы можете прямо сейчас перейдя <a href="https://bit.ly/3bLtzze">по этой ссылке</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b947734e1e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Workout at home with Fitmer]]></title>
            <link>https://medium.com/@vivchar/%D1%82%D1%80%D0%B5%D0%BD%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B8-%D0%BD%D0%B0-%D1%81%D0%B0%D0%BC%D0%BE%D0%B8%D0%B7%D0%BE%D0%BB%D1%8F%D1%86%D0%B8%D0%B8-c-fitmer-ed6186525817?source=rss-2a5602aa78ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed6186525817</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[timer]]></category>
            <category><![CDATA[workout]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[tabata]]></category>
            <dc:creator><![CDATA[Vitaly Vivchar]]></dc:creator>
            <pubDate>Sun, 03 May 2020 13:01:35 GMT</pubDate>
            <atom:updated>2020-05-06T16:06:20.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>Home workout with Fitmer</h3><p>Today, in connection with the coronavirus pandemic, we are forced to observe an order of self-isolation. There are people already pretty bored, but I think this is a very useful time for self-development. For several weeks I worked from 13 to 16 hours in a day and a really hope that it is not in vain. The result is an application I created for your workouts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGbuDijzK8xZwgKOAF4_EQ.png" /></figure><h3>FITMER</h3><p>This is an interval fitness timer that can improve the quality of your workouts. Since at the moment all sports facilities are not functioning, and not everyone can do it himself. This application will serve as an excellent tool for organizing any home workouts (yoga, pilates, stretching, strength, cross-fit, cardio, aerobics and other interval training).</p><h3>First launch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*7JW7V8LDJXvKS2TTPZSucw.png" /></figure><p>At the first start, you will see a minimalistic design in dark colors. I decided to keep your attention on the important things, then I highlighted it in bright green.</p><p>A demo training has been prepared on the start page, which you can immediately launch with a simple click and check how it works.</p><p>Of course, you want to create your own training, for this you need to click on the plus button.</p><p>If necessary, you can edit existing workouts. For example, after several time, you want to upgrade them — click on the pencil button in any workout.</p><h4>Editing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*2eeRejepSmJxmrNKHM5Lkg.png" /></figure><p>When you click on the plus button or pencil, you will be taken to the training configuration page.</p><p>What you should pay attention to? Any training session can consist of three types of “Sections / block” — so far I haven’t come up with a better name, so let’s use this term. Each section is highlighted in the picture with a dark background.</p><p><strong>Section “Relax”</strong></p><p>This is the simplest view that is used to separate the other two types of sections in breaks so that you can catch your breath. In this section, only the seconds in your rest are available for change.</p><p><strong>Section «Exercise»</strong></p><p>This is a traditional type of exercise in any workout — a combination of a specific exercise and rest that needs to be repeated a several times, in other words, the number of approaches. Here the volume of given work is available to change — time under load, and a rest time and the number of approaches / cycles are available to change too .</p><p>I also want to note that in this section the last rest in the last cycle / approach will be automatically skipped and the next section will be behind it. This is necessary for adding explicit rests between sections excluding the available rest in the last exercise. Actually, a standard training takes place in exactly the same way. Rests between sets and rests between exercises are never summarize — after the final approach, there is always rest before the next exercise.</p><p><strong>Section «Set»</strong></p><p>This is the most difficult type of sections. Here you can combine any sequence of rests, exercises based on your goals. There is an opportunity to add two or more consecutive exercises, including rest after exercise — this is an interpretation of classic sets and super sets in training.</p><p><em>Note</em>: do not add a few rests in a row — the timer will scold freeloaders and will not allow you to save the workout.</p><h3>Start the Timer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ccD_gY0mVTOjp0gH9hAEKg.png" /></figure><p>To start just click on the start page for any workout. The timer will load it and will be ready, for your command it will start counting the time of zero block, this is time to prepare before your first block, you need to prepare during this time.</p><p>In the center of the screen you will see a countdown of the current state of your workout — it can be a rest or an exercise. You see two progresses around the figure — the internal one is the progress of the current state, and the external one is the whole workout. The whole countdown of the whole workout is visible under the main timer value also.</p><p>At the bottom of the screen you can see sections are vertically arranged and highlighted with a dark background, the section number and the amount of time remaining at the header. Inside the section you can see all of your created sequences — combinations of rest and exercise. There are all your sections are the same — there is no point in distinguishing them. Any set or training is just a set of rest and work sequence.</p><p>If necessary, you can skip your workouts and return to the previous, to view the available workouts — scroll, to start, pause and switch — use the special control panel above the unit.</p><h3>Sound accompaniment</h3><p>At the beginning of each “work” you will hear a “whistle” — the start command — it’s time to work!</p><p>As soon as your work will finished— timer will play “beep” for each three seconds before the finish of the current state so that you have time to prepare.</p><p>At the end of the work you will hear a “gong” — it means it’s time to relax. At the end of the rest, timer will count three seconds also, so that you have time to take a position in advance.</p><p>When the whole training is over — you will hear a “triple gong” — you’re done!</p><h3>Conclusion</h3><p>I would like this application will be the best tool for your home training, so I am open to all types of reviews. Let’s make it really convenient and useful together.</p><p>This application is already available on all platforms. You can try the application right now by clicking <a href="https://bit.ly/3bLtzze">on this link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed6186525817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying the work with RecyclerView]]></title>
            <link>https://medium.com/android-news/simplifying-the-work-with-recyclerview-a64027bca8c3?source=rss-2a5602aa78ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/a64027bca8c3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[generic-recycler-view]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Vitaly Vivchar]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 12:01:32 GMT</pubDate>
            <atom:updated>2018-04-18T08:49:30.388Z</atom:updated>
            <content:encoded><![CDATA[<p>There are already a lot of articles on this topic, all of them mainly offer solutions for convenient reusing of cells in <em>RecyclerView</em>. Today we will go a little further and approach the simplicity comparable with <em>DataBinding</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*CL-8zaeo84wze2Q2-OM5Vg.png" /></figure><p>If you don’t already use <em>DataBinding</em> for lists and do it in the old manner — then this article is for you.</p><h3><strong>Introduction</strong></h3><p>To quickly dive into the context of the article, let’s analyze what we now have when using the universal adapter from the previous articles:</p><ol><li><a href="https://medium.com/@vivchar/a-recyclerview-with-multiple-item-types-dfba3979050">A RecyclerView with multiple item types</a>;</li><li><a href="https://medium.com/@vivchar/easy-handling-of-lists-rendererrecyclerviewadapter-part-2-3b18c8ea6f1b">Easy handling of lists — RendererRecyclerViewAdapter.</a></li></ol><p>To implement the simplest list using <em>RendererRecyclerViewAdapter v2.x.x</em> you need to:</p><p>1. Add <em>ViewModel</em> interface for each cell model:</p><pre>public class YourModel implements ViewModel {</pre><pre>    //...</pre><pre>    public String getYourText() { … }</pre><pre>}</pre><p>2. Make a classic <em>ViewHolder</em> implementation:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;TextView<br>     android:id = &quot;@+id/yourTextView&quot;<br>     xmlns:android = &quot;http://schemas.android.com/apk/res/android&quot;<br>     android:layout_width = &quot;match_parent&quot;<br>     android:layout_height = &quot;50dp&quot;<br>/&gt;</pre><pre>public class YourViewHolder extends RecyclerView.ViewHolder {</pre><pre>    public<br>    TextView yourTextView;</pre><pre>    public<br>    RectViewHolder(View v) {<br>        super(itemView);<br>        yourTextView = (TextView) v.findViewById(R.id.yourTextView);<br>    }</pre><pre>    //...<br>}</pre><p>3. Implement <em>ViewRenderer</em>:</p><pre>public class YourViewRenderer <br>    extends ViewRenderer&lt;YourModel, YourViewHolder&gt; {</pre><pre>    public<br>    YourViewRenderer(Class&lt;YourModel&gt; type, Context context) {<br>        super(type, context);<br>    }</pre><pre>    public<br>    void bindView(YourModel model, YourViewHolder holder) {<br>        holder.yourTextView.setText(model.getYourText());<br>        //...<br>    }</pre><pre>    public<br>    YourViewHolder createViewHolder(ViewGroup parent) {<br>        return new YourViewHolder(inflate(<br>                         R.layout.your_layout,<br>                         parent<br>               ));<br>    }<br>}</pre><p>4. Initialize Adapter and give the necessary data to it:</p><pre>RendererRecyclerViewAdapter a = new RendererRecyclerViewAdapter();<br>a.registerRenderer(new YourViewRenderer(<br>    YourModel.class,<br>    getContext()<br>));<br>a.setItems(getYourModelList());</pre><p>Knowing about <em>DataBinding</em> and its simple implementation, there is a question — why so much extra code, the main thing is binding — a comparison of these models with layout. From binding you can not go anywhere.</p><p>In the classical implementation, we use the <em>bindView()</em> method, everything else is just a preparation for it (implementation and initialization <em>ViewHolder</em>).</p><h3><strong>What is ViewHolder and why is it needed?</strong></h3><p>In <em>Fragment</em>, <em>Activity</em> and <em>RecyclerView</em>, we often use this pattern, so what do we need it for? What are the pros and cons of it?</p><p>Advantages:</p><ul><li>No need to use <em>findViewById()</em> each time and to specify an ID;</li><li>No need to always spend CPU time searching for a specific ID in xml;</li><li>Convenient access to the element through the created field.</li></ul><p>Disadvantages:</p><ul><li>You have to write an additional class;</li><li>You have to create a field with a similar name for each ID in xml;</li><li>When you change an ID, you need to rename the field in <em>ViewHolder</em>.</li></ul><p>With some disadvantages, third-party libraries are fine, for example ButterKnife, but in the <em>RecyclerView</em> case it will not help us much — we will not get rid of <em>ViewHolder</em>. In <em>DataBinding</em> we can create a universal ViewHolder, because the Binding responsibility is in XML. What can we do?</p><h3><strong>Creating Default ViewHolder</strong></h3><p>If we use the standard implementation of <em>RecyclerView.ViewHolder</em> as a stub in <em>createViewHolder()</em> method, we will have to use <em>findViewById</em> method every time in <em>bindView()</em>, let’s sacrifice the Advantages and see what happens.</p><p>Since this is an abstract class, let’s add an empty implementation of the new default ViewHolder:</p><pre>public class ViewHolder extends RecyclerView.ViewHolder { </pre><pre>    public<br>    ViewHolder(View itemView) {<br>      super(itemView);<br>    }<br>}</pre><p>We replace <em>ViewHolder</em> in our <em>ViewRenderer</em>:</p><pre>public class YourViewRenderer<br>    extends ViewRenderer&lt;YourModel, ViewHolder&gt; {</pre><pre>    public<br>    YourViewRenderer(Class&lt;YourModel&gt; type, Context ctx) {<br>        super(type, ctx);<br>    }</pre><pre>    public<br>    void bindView(YourModel m, ViewHolder h) {<br>        TextView textView =((TextView)h.itemView.findViewById(R.id.yourTextView));<br>        textView.setText(m.getYourText());     <br>    }</pre><pre>    public<br>    ViewHolder createViewHolder(ViewGroup parent) {<br>        return new ViewHolder(inflate(<br>            R.layout.your_layout,<br>            parent<br>        ));<br>    }<br>}</pre><p>The resulting advantages:</p><ul><li>No need to implement <em>ViewHolder</em> for each cell;</li><li>The implementation of createViewHolder method can be moved to the base class.</li></ul><p>Now we will analyze the lost pluses. Since we are viewing <em>ViewHolder</em> within <em>RecyclerView</em>, we will only refer to it in <em>bindView()</em> method. Therefore, the first and third items are not very useful to us:</p><ul><li>No need to use <em>findViewById()</em> each time and to specify an ID;</li><li>Convenient access to the element through the created field.</li></ul><p>But we can not sacrifice performance, so let’s decide something. The implementation of <em>ViewHolder</em> allows us to “cache” the found view. So let’s add it to the default <em>ViewHolder</em>:</p><pre>public class ViewHolder extends RecyclerView.ViewHolder {</pre><pre>    private final SparseArray&lt;View&gt; mCachedViews = new SparseArray&lt;&gt;();</pre><pre>    public ViewHolder(View itemView) {<br>        super(itemView);<br>    }</pre><pre>    public &lt;T extends View&gt; T find(int ID) {<br>        return (T) findViewById(ID);<br>    }</pre><pre>    private View findViewById(int ID) {<br>        final View cachedView = mCachedViews.get(ID);<br>        if (cachedView != null) {<br>            return cachedView;<br>        }<br>        final View view = itemView.findViewById(ID);<br>        mCachedViews.put(ID, view);<br>        return view;<br>    }<br>}</pre><p>Thus, after the first call of <em>bindView()</em>, the <em>ViewHolder</em> will know about all its views and subsequent calls will use cached values.</p><p>Now we’ll remove all unnecessary ones from the base ViewRender, add a new parameter to the constructor to transfer the ID of the file and see what happens:</p><pre>public class YourViewRenderer<br>    extends ViewRenderer&lt;YourModel, ViewHolder&gt; {</pre><pre>    public YourViewRenderer(int layoutID,<br>                            Class&lt;YourModel&gt; type,<br>                            Context context) {<br>        super(layoutID, type, context);<br>    }</pre><pre>    public void bindView(YourModel model, ViewHolder holder) {<br>        ((TextView)holder.find(R.id.yourTextView))<br>            .setText(model.getYourText());<br>    }<br>}</pre><p>In terms of the amount of code, it looks much better: one constructor remains and it is always the same. And do we really need to create a new <em>ViewRenderer</em> each time for the sake of one method? I think not. We solve this problem through delegation and an additional parameter in the constructor, let’s have a look:</p><pre>public class ViewBinder&lt;M extends ViewModel&gt;<br>    extends ViewRenderer&lt;M, ViewHolder&gt; {</pre><pre>    private final Binder mBinder;</pre><pre>    public ViewBinder(int layoutID,<br>                      Class&lt;M&gt; type,<br>                      Context context,<br>                      Binder&lt;M&gt; binder) {<br>        super(layoutID, type, context);<br>        mBinder = binder;<br>    }</pre><pre>    public void bindView(M model, ViewHolder holder) {<br>        mBinder.bindView(model, holder);<br>    }</pre><pre>    public interface Binder &lt;M&gt; {<br>        void bindView(M model, ViewHolder holder);<br>    }<br>}</pre><p>Adding a cell is shortened to:</p><pre>...</pre><pre>adapter.registerRenderer(new ViewBinder&lt;&gt;(<br>        R.layout.your_layout, <br>        YourModel.class, <br>        getContext(),<br>        (model, holder) -&gt; {<br>            ((TextView)holder.find(R.id.yourTextView))<br>                .setText(model.getYourText());<br>        }<br>));</pre><pre>...</pre><p>Let’s list the advantages of this solution:</p><ul><li>No need to create <em>ViewHolder</em> each time and create variables for views;</li><li>No need to create <em>ViewRenderer</em> each time and write extra code;</li><li>No need to rename anything when changing the view ID;</li><li>All the data about the view (layoutID, concreteViewID, cast) are in one place.</li></ul><p>To avoid a lot of casts and simplify binding I added main methods to ViewHolder:</p><pre>public ViewHolder setText(int ID, CharSequence text) {   <br>    ((TextView) find(ID)).setText(text);<br>    return this;<br>}</pre><pre>public ViewHolder setTextSize(int ID, float size) {<br>    ((TextView) find(ID)).setTextSize(size);<br>    return this;<br>}</pre><pre>public ViewHolder setImageDrawable(int ID, Drawable drawable) {<br>    ((ImageView) find(ID)).setImageDrawable(drawable);<br>    return this;<br>}</pre><pre>public ViewHolder setAlpha(int ID, int alpha) {<br>    find(ID).setAlpha(alpha);<br>    return this;<br>}</pre><pre>//other main methods</pre><h3>Conclusion</h3><p>By sacrificing small advantages we’ve got a fairly simple solution for adding new cells, this will undoubtedly simplify the work with <em>RecyclerView</em>.</p><p>The article provides only a simple example for understanding, the current implementation allows:</p><ul><li>Working with Nested RecyclerView;</li><li>Saving and restoring the state of the cell in the scroll;</li><li>Working with Payload when using DiffUtil;</li><li>Adding Load More Indicator when loading data.</li></ul><h3>Github Library</h3><p><a href="https://github.com/vivchar/RendererRecyclerViewAdapter">vivchar/RendererRecyclerViewAdapter</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a64027bca8c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/simplifying-the-work-with-recyclerview-a64027bca8c3">Simplifying the work with RecyclerView</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily add Nested RecyclerView]]></title>
            <link>https://medium.com/android-news/easy-handling-of-lists-rendererrecyclerviewadapter-part-2-3b18c8ea6f1b?source=rss-2a5602aa78ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b18c8ea6f1b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Vitaly Vivchar]]></dc:creator>
            <pubDate>Tue, 09 Jan 2018 14:33:29 GMT</pubDate>
            <atom:updated>2018-05-05T14:04:44.093Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*VG98RxaEW7f8jZOwF5uGgg.png" /></figure><p>Last time we <a href="https://medium.com/@vivchar/a-recyclerview-with-multiple-item-types-dfba3979050">optimized the way we worked with RecyclerView</a>, and we also learned how to reuse cells in different lists and easily add new cells. <br> <br> Today I’ll be explaining two things:</p><p>· simplifying <a href="https://developer.android.com/reference/android/support/v7/util/DiffUtil.html">DiffUtil</a> support in this implementation;</p><p>· adding support for nesting RecyclerView.</p><p>If you liked the previous post, then you’ll like this one, too.</p><h3>DiffUtil</h3><p>I think there’s no need to explain what DiffUtil is. Every Android developer has probably used it in projects and took advantage of nice extras like animation and improved performance. <br> <br> A few days after the first article has gone live, I’ve got a <a href="https://github.com/vivchar/RendererRecyclerViewAdapter/pull/2">pull request</a> with a DiffUtil implementation. Let’s see how it’s implemented. You may remember that we ended up with an adapter with public method setItems(ArrayList &lt;ItemModel&gt; items). Here it’s not very convenient for us to use DiffUtil, and we’ll need to save the old copy of the list somewhere. So, we would be getting something like this:</p><pre>…</pre><pre>final MyDiffCallback diffCallback = new MyDiffCallback(getOldItems(), getNewItems());</pre><pre>final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);</pre><pre>mRecyclerViewAdapter.setItems(getNewItems());</pre><pre>diffResult.dispatchUpdatesTo(mRecyclerViewAdapter);</pre><pre>…</pre><p>Classic implementation of DiffUtil.Callback:</p><pre>public class MyDiffCallback extends DiffUtil.Callback <br>{</pre><pre>    private final List&lt;BaseItemModel&gt; mOldList;<br>    private final List&lt;BaseItemModel&gt; mNewList;</pre><pre>    public MyDiffCallback(List&lt;BaseItemModel&gt; oldList,  <br>                          List&lt;BaseItemModel&gt; newList) {<br>        mOldList = oldList;<br>        mNewList = newList;<br>    }<br>     <br>    @Override<br>    public int getOldListSize() {<br>        return mOldList.size();<br>    }<br>     <br>    @Override<br>    public int getNewListSize() {<br>        return mNewList.size();<br>    }</pre><pre>    @Override<br>    public boolean areItemsTheSame(int old, int new) {<br>        return mOldList.get(old).getID() <br>               == mNewList.get(new).getID();<br>    }</pre><pre>    @Override<br>    public boolean areContentsTheSame(int old, int new) {<br>        BaseItemModel oldItem = mOldList.get(old);           <br>        BaseItemModel newItem = mNewList.get(new);              <br>        return oldItem.equals(newItem);     <br>    }</pre><pre>    public Object getChangePayload(int old, int new) {<br>        return super.getChangePayload(old, new);<br>    }<br>}</pre><p>And an extended ItemModel interface:</p><pre>public interface BaseItemModel extends ItemModel {<br>    int getID();<br>}</pre><p>This is quite implementable and not complicated. However, if we use this several times in a project, then let us think if we really need so much of the same code. Let us carry over the reusable elements into our own DiffUtil.Callback implementation:</p><pre>public abstract static class DiffCallback <br>    &lt;BM extends ItemModel&gt; <br>    extends DiffUtil.Callback <br>{</pre><pre>    private final List&lt;BM&gt; mOldItems = new ArrayList&lt;&gt;();<br>    private final List&lt;BM&gt; mNewItems = new ArrayList&lt;&gt;();</pre><pre>    void setItems(List&lt;BM&gt; oldItems, List&lt;BM&gt; newItems) {<br>        mOldItems.clear();<br>        mOldItems.addAll(oldItems);<br>        mNewItems.clear();<br>        mNewItems.addAll(newItems);<br>    }</pre><pre>    @Override<br>    public int getOldListSize() {<br>        return mOldItems.size();<br>    }</pre><pre>    @Override<br>    public int getNewListSize() {<br>        return mNewItems.size();<br>    }</pre><pre>    @Override<br>    public boolean areItemsTheSame(int old, int new) {<br>        return areItemsTheSame(<br>            mOldItems.get(old),   <br>            mNewItems.get(new)<br>        );<br>    }</pre><pre>    public abstract boolean areItemsTheSame(BM oldItem, BM newItem);</pre><pre>    @Override<br>    public boolean areContentsTheSame(int old, int new) {<br>        return areContentsTheSame(<br>            mOldItems.get(old),<br>            mNewItems.get(new)<br>        );<br>    }</pre><pre>    public abstract boolean areContentsTheSame(BM oldItem, <br>                                               BM newItem);<br>    …<br>}</pre><p>All in all, we managed to make a rather versatile implementation. We avoided unnecessary lines of code and were able to focus on the important methods: areItemsTheSame() and areContentsTheSame(). Those must be implemented and those may differ. <br> <br> I’m omitting the implementation of getChangePayload() and you can see it in the <a href="https://github.com/vivchar/RendererRecyclerViewAdapter/blob/master/rendererrecyclerviewadapter/src/main/java/com/github/vivchar/rendererrecyclerviewadapter/DiffCallback.java">source</a>.<br> <br> Now we can add one more method with DiffUtil support in our adapter:</p><pre>public void setItems(List&lt;ItemModel&gt; items, <br>                     DiffCallback callback) {<br>    callback.setItems(mItems, items);<br>    final DiffResult diffResult = DiffUtil.calculateDiff(callback);<br>    mItems.clear();<br>    mItems.addAll(items);<br>    diffResult.dispatchUpdatesTo(this);<br>}</pre><p>That’s about all with DiffUtil, and now we can use our abstract class DiffCallback if necessary. And we’ll be implementing just two methods. <br> <br> I think now that we’ve warmed up and refreshed our memories, we can move on to more interesting things.</p><p><strong>Nesting RecyclerViews</strong></p><p>One way or another, nested lists find their ways into our applications, at customer request or at GUI designers discretion,. Until recently I disregarded them as I faced the following problems:</p><p>· complex implementation of the cell that contains RecyclerView;</p><p>· complex data updating in nesting cells;</p><p>· non-reusable nesting cells;</p><p>· code reduplication;</p><p>· too complex click forwarding from nesting cells into the root location — Fragment/Activity;</p><p>Some of these problems are questionable and easily addressable. Some will go away if we plug in <a href="https://github.com/vivchar/RendererRecyclerViewAdapter">our optimized adapter</a> from the first article :) However, we’ll have to face the complexity of implementation at least. Let us articulate our requirements:</p><p>· easy addition of new types of nested cells;</p><p>· reusability of a cell type for both nested and parent list items;</p><p>· simple implementation;</p><p>It’s important to note that I have divided the concepts of a cell and a list item:<br> <strong>list item</strong> — the entity used in RecyclerView.<br> <strong>cell</strong> — a set of classes that allow for showing one list item type. In our case, this is an implementation of already known classes and interfaces: ViewRenderer, ItemModel, ViewHolder.<br> <br> Let’s sum up what we have at our disposal. ItemModel is the key interface, and it’s obvious it will be convenient for us to work with it later on. Our composite model must include child models, so we add a new interface:</p><pre>public interface CompositeItemModel extends ItemModel {<br>    List&lt;ItemModel&gt; getItems();<br>}</pre><p>Looks decent. Accordingly, composite ViewRenderer must know about child renderers, so we add:</p><pre>public abstract class CompositeViewRenderer <br>    &lt;M extends CompositeItemModel, VH extends CompositeViewHolder&gt; <br>    extends ViewRenderer&lt;M, VH&gt; <br>{</pre><pre>    private final ArrayList&lt;ViewRenderer&gt; mRenderers = <br>                                                new ArrayList&lt;&gt;();</pre><pre>    public CompositeViewRenderer(int viewType, Context context) {<br>        super(viewType, context);<br>    }</pre><pre>    public CompositeViewRenderer(int viewType, <br>                                 Context context, <br>                                 ViewRenderer… renderers) {<br>        super(viewType, context);<br>        Collections.addAll(mRenderers, renderers);<br>    }</pre><pre>    public CompositeViewRenderer registerRenderer(ViewRenderer r) {<br>        mRenderers.add(r);<br>        return this;<br>    }</pre><pre>    public void bindView(M model, VH holder) {}</pre><pre>    public VH createViewHolder(ViewGroup parent) {<br>        return …; <br>    }<br>    …<br>}</pre><p>Here I’ve added two ways of adding child renderers, and I’m sure we’ll put them to good use. <br> Also, please note generic CompositeViewHolder. This will be a separate class for composite ViewHolder, and I don’t know yet what it will contain. Now let us continue working with CompositeViewRenderer. We have two required methods left — bindView() and createViewHolder(). We should initialize the adapter in createViewHolder() and then familiarize it with the renderers. As for bindView(), we’ll do a simple default item updating:</p><pre>public abstract class CompositeViewRenderer <br>    &lt;M extends CompositeItemModel, VH extends CompositeViewHolder&gt; <br>    extends ViewRenderer&lt;M, VH&gt; <br>{</pre><pre>    private final ArrayList&lt;ViewRenderer&gt; mRenderers = <br>                                                new ArrayList&lt;&gt;();<br>    private RendererRecyclerViewAdapter mAdapter;</pre><pre>    …</pre><pre>    public void bindView(M model, VH holder) {<br>        mAdapter.setItems(model.getItems());<br>        mAdapter.notifyDataSetChanged();<br>    }</pre><pre>    public VH createViewHolder(ViewGroup parent) {<br>        mAdapter = new RendererRecyclerViewAdapter();</pre><pre>        for (final ViewRenderer renderer : mRenderers) {<br>            mAdapter.registerRenderer(renderer);<br>        }<br>        return ???;<br>    }<br>    …<br>}</pre><p>Almost there! As it turned out, for such an implementation we’ll need viewHolder itself in createViewHolder(). We cannot initialize it here, so we create a separate abstract method. Here, we may want to familiarize our adapter with RecyclerView. We could borrow it from CompositeViewHolder. We haven’t implemented it yet, so let’s do it:</p><pre>public abstract class CompositeViewHolder <br>    extends RecyclerView.ViewHolder <br>{</pre><pre>    public RecyclerView mRecyclerView;</pre><pre>    public CompositeViewHolder(View itemView) {<br>       super(itemView);<br>    }<br>}</pre><pre>public abstract class CompositeViewRenderer <br>    &lt;M extends CompositeItemModel, VH extends CompositeViewHolder&gt; <br>    extends ViewRenderer&lt;M, VH&gt; <br>{</pre><pre>    public VH createViewHolder(ViewGroup parent) {<br>        mAdapter = new RendererRecyclerViewAdapter();</pre><pre>        for (final ViewRenderer renderer : mRenderers) {<br>            mAdapter.registerRenderer(renderer);<br>        }</pre><pre>        VH viewHolder = createCompositeViewHolder(parent);<br>        viewHolder.mRecyclerView.setLayoutManager(<br>            createLayoutManager()<br>        );<br>        viewHolder.mRecyclerView.setAdapter(mAdapter);</pre><pre>        return viewHolder;<br>    }</pre><pre>    public abstract VH createCompositeViewHolder(ViewGroup parent);</pre><pre>    protected RecyclerView.LayoutManager createLayoutManager() {<br>        return new LinearLayoutManager(<br>            getContext(), HORIZONTAL, false<br>        );<br>    }</pre><pre>    …<br>}</pre><p>That’s right! I’ve added the default implementation with LinearLayoutManager :( I thought this would bring more profit, and we’ll overload the method if necessary and set another LayoutManager.<br> <br> It seems that’s about it. Now we have specific classes to implement, and we’ll see what we get:</p><pre>public class SomeCompositeItemModel implements CompositeItemModel <br>{</pre><pre>    public static final int TYPE = 999;<br>    private int mID;<br>    private final List&lt;ItemModel&gt; mItems; <br>    <br>    public SomeCompositeItemModel(int ID, List&lt;ItemModel&gt; items) {<br>       mID = ID; <br>       mItems = items; <br>   } </pre><pre>   public int getID() { <br>       return mID; <br>   } <br>   <br>   public int getType() { <br>       return TYPE; <br>   } <br>   <br>   public List&lt;ItemModel&gt; getItems() { <br>       return mItems;<br>   } <br>}</pre><pre>public class SomeCompositeViewHolder extends CompositeViewHolder <br>{ </pre><pre>   public SomeCompositeViewHolder(View view) { <br>      super(view); <br>      mRecyclerView = view.findViewById(R.id.recycler_view); <br>   } <br>}</pre><pre>public class SomeCompositeViewRenderer <br>    extends CompositeViewRenderer<br>    &lt;SomeCompositeModel, SomeCompositeViewHolder&gt; <br>{ <br> <br>   public SomeCompositeViewRenderer(int viewType, Context context) { <br>       super(viewType, context); <br>   } </pre><pre>   public SomeCompositeViewHolder createCompositeViewHolder(<br>                                            ViewGroup parent) {<br>       return new SomeCompositeViewHolder(<br>           inflate(R.layout.layout, parent)<br>       ); <br>   } <br>}</pre><p>We register our composite renderer:</p><pre>public class SomeActivity extends AppCompatActivity <br>{</pre><pre>    protected void onCreate(final Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        …</pre><pre>        SomeCompositeViewRenderer composite = new SomeCompositeViewRenderer(<br>             SomeCompositeItemModel.TYPE, <br>             this, <br>             new SomeViewRenderer(SomeModel.TYPE, this, mListener)<br>        );</pre><pre>        mRecyclerViewAdapter.registerRenderer(composite);</pre><pre>        …<br>    }<br>    …<br>}</pre><p>As seen from the last sample, to subscribe to clicks we just pass the necessary interface into the renderer’s constructor. Thus, our root location implements this interface and is aware of all the required clicks.</p><p>Click forwarding example:</p><pre>public class SomeViewRenderer <br>    extends ViewRenderer&lt;SomeModel, SomeViewHolder&gt; <br>{ </pre><pre>    private final Listener mListener; </pre><pre>    public SomeViewRenderer(int type, Context context, Listener l) { <br>        super(type, context); <br>        mListener = l; <br>    } </pre><pre>    public void bindView(SomeModel model, SomeViewHolder holder) {<br>        … </pre><pre>        holder.itemView.setOnClickListener(new OnClickListener() { <br>            public void onClick(final View view) {<br>                mListener.onSomeItemClicked(model); <br>            }<br>        });<br>    } </pre><pre>    … <br>    public interface Listener { <br>        void onSomeItemClicked(SomeModel model); <br>    } <br>}</pre><p><strong>Conclusion</strong><br> <br> We’ve achieved sufficient versatility and flexibility while working with nested lists. We’ve essentially simplified the process of adding composite cells. Now we can easily add new composite cells and easily combine individual cells in nested and parent lists.</p><h3>Next article</h3><ul><li><a href="https://android.jlelse.eu/simplifying-the-work-with-recyclerview-a64027bca8c3">Simplifying the work with RecyclerView</a></li><li><a href="https://github.com/vivchar/RendererRecyclerViewAdapter">vivchar/RendererRecyclerViewAdapter</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b18c8ea6f1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/easy-handling-of-lists-rendererrecyclerviewadapter-part-2-3b18c8ea6f1b">How to easily add Nested RecyclerView</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A RecyclerView with multiple item types]]></title>
            <link>https://medium.com/android-news/a-recyclerview-with-multiple-item-types-dfba3979050?source=rss-2a5602aa78ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfba3979050</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androidarsenal]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[recyclerview]]></category>
            <dc:creator><![CDATA[Vitaly Vivchar]]></dc:creator>
            <pubDate>Mon, 30 Oct 2017 04:19:37 GMT</pubDate>
            <atom:updated>2018-01-24T14:05:25.346Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YERHvVC6yRxE37q6JqPJsw.jpeg" /></figure><h3>Motivation</h3><p>As of late, I often had to rework a lot of list adapters. And each time I was desperate as the adapter contained the business logic, networking queries, application routing and much more. All this was very difficult to change. At first I was just moving the unrelated stuff from adapters to presenters, fragments and other classes. Eventually, I realized that it would not hurt if I could:</p><ol><li>“Secure” my adapters against the introduction of inappropriate logic;</li><li>Reuse cell bindings;</li><li>Achieve some versatility when working with different cell types.</li></ol><p>If you are familiar with some of these problems, then welcome under the cut. Looking for an off-the-shelf solution, I found AdapterDelegates but it failed to achieve the first of my objectives.</p><h3>Requirements</h3><p>To start with, I have highlighted several requirements that I have already articulated:</p><ul><li>it must work with RecyclerView without implementing a new adapter;</li><li>I must be able to reuse cells in another RecyclerView;</li><li>I must be able to easily add other cell types into RecyclerView.</li></ul><h3>Implementation</h3><p>First I’ve taken a look at things I always do within the adapter, to do that I created a test implementation and analyzed the methods that I used:</p><pre><strong>public</strong> <strong>class</strong> <strong>Test</strong> <strong>extends</strong> RecyclerView<strong>.</strong>Adapter <strong>{</strong></pre><pre>	<strong>@Override</strong><br>	<strong>public</strong> ViewHolder <strong>onCreateViewHolder(final</strong> ViewGroup parent<strong>,</strong> <strong>final</strong> <strong>int</strong> viewType<strong>)</strong> <strong>{</strong><br>	<strong>}</strong></pre><pre>	<strong>@Override</strong> <strong>public</strong> <strong>void</strong> <strong>onBindViewHolder(final</strong> ViewHolder holder<strong>,</strong> <strong>final</strong> <strong>int</strong> position<strong>)</strong> <strong>{</strong><br>	<strong>}</strong></pre><pre>	<strong>@Override</strong><br>	<strong>public</strong> <strong>int</strong> <strong>getItemCount()</strong> <strong>{</strong><br>		<strong>return</strong> 0<strong>;</strong><br>	<strong>}</strong></pre><pre>	<strong>public</strong> <strong>void</strong> <strong>setItems(@NonNull</strong> <strong>final</strong> ArrayList items<strong>)</strong> <strong>{</strong><br>	<strong>}</strong><br><strong>}</strong></pre><p>There were 4 methods overall. setItems() is the one that draws attention. It must be able to accept different model lists, so we create an empty interface and update the code in our test adapter:</p><pre><strong>public</strong> <strong>interface</strong> <strong>ItemModel</strong> <strong>{</strong> <strong>}</strong></pre><pre><strong>public</strong> <strong>class</strong> <strong>Test</strong> <strong>extends</strong> RecyclerView<strong>.</strong>Adapter <strong>{</strong></pre><pre>        <strong>@NonNull</strong><br>	<strong>private</strong> <strong>final</strong> ArrayList<strong>&lt;</strong>ItemModel<strong>&gt;</strong> mItems <strong>=</strong> <strong>new</strong> ArrayList<strong>&lt;&gt;();</strong></pre><pre>        <strong>....</strong><br>	<br>	<strong>@Override</strong><br>	<strong>public</strong> <strong>int</strong> <strong>getItemCount()</strong> <strong>{</strong><br>                <strong>return</strong> mItems<strong>.</strong>size<strong>();</strong><br>	<strong>}</strong></pre><pre>        <strong>public</strong> <strong>void</strong> <strong>setItems(@NonNull</strong> <strong>final</strong> ArrayList<strong>&lt;</strong>ItemModel<strong>&gt;</strong> items<strong>)</strong> <strong>{</strong><br>		mItems<strong>.</strong>clear<strong>();</strong><br>		mItems<strong>.</strong>addAll<strong>(</strong>items<strong>);</strong><br>	<strong>}</strong><br><strong>}</strong></pre><p>Now we must figure something out with onCreateViewHolder() and onBindViewHolder(). If I want to enable my adapter to bind different viewers, then it should better be able to delegate it somewhere. It will allow us to reuse the implementation afterwards. We create an abstract class that will be able to handle only one cell type and a specific ViewHolder of course. To this end we use generics in order to avoid type casts. Let’s call it ViewRenderer (it’s the best I could think of).</p><pre><strong>public</strong> <strong>abstract</strong> <strong>class</strong> <strong>ViewRenderer</strong> <strong>&lt;</strong>M <strong>extends</strong> ItemModel<strong>,</strong> VH <strong>extends</strong> RecyclerView<strong>.</strong>ViewHolder<strong>&gt;</strong> <strong>{</strong></pre><pre>	<strong>public</strong> <strong>abstract</strong>	<strong>void</strong> <strong>bindView(@NonNull</strong> M model<strong>,</strong> <strong>@NonNull</strong> VH holder<strong>);</strong></pre><pre>	<strong>@NonNull</strong><br>	<strong>public</strong> <strong>abstract</strong>	VH <strong>createViewHolder(@Nullable</strong> ViewGroup parent<strong>);</strong><br><strong>}</strong></pre><p>Let’s try using it in our adapter. Let’s rename the adapter into something that makes more sense and then update the code:</p><pre><strong>public</strong> <strong>class</strong> <strong>RendererRecyclerViewAdapter</strong> <strong>extends</strong> RecyclerView<strong>.</strong>Adapter <strong>{</strong></pre><pre>        <strong>...</strong></pre><pre>        <strong>private</strong> ViewRenderer mRenderer<strong>;</strong></pre><pre>	<strong>@Override</strong><br>	<strong>public</strong> RecyclerView<strong>.</strong>ViewHolder <strong>onCreateViewHolder(final</strong> ViewGroup parent<strong>,</strong> <strong>final</strong> <strong>int</strong> viewType<strong>)</strong> <strong>{</strong><br>		<strong>return</strong> mRenderer<strong>.</strong>createViewHolder<strong>(</strong>parent<strong>);</strong><br>	<strong>}</strong></pre><pre>	<strong>@Override</strong><br>	<strong>public</strong> <strong>void</strong> <strong>onBindViewHolder(final</strong> RecyclerView<strong>.</strong>ViewHolder holder<strong>,</strong> <strong>final</strong> <strong>int</strong> position<strong>)</strong> <strong>{</strong><br>		mRenderer<strong>.</strong>bindView<strong>(</strong>item<strong>,</strong> holder<strong>);</strong><br>	<strong>}</strong></pre><pre>        <strong>public</strong> <strong>void</strong> <strong>registerRenderer(@NonNull</strong> <strong>final</strong> ViewRenderer renderer<strong>)</strong> <strong>{</strong><br>                mRenderer <strong>=</strong> renderer<strong>;</strong><br>	<strong>}</strong><br>	<br>        <strong>...</strong><br><strong>}</strong></pre><p>It all looks okay for now. Still, our adapter must be able to work with multiple view types. To that end, the adapter has getItemViewType(), and we override it in the adapter. Let’s try to get cell type directly from the model by adding getItemViewType() into the interface and updating the adapter’s method:</p><pre><strong>public</strong> <strong>interface</strong> <strong>ItemModel</strong> <strong>{</strong><br>	<strong>int</strong> <strong>getType();</strong><br><strong>}</strong></pre><pre><strong>public</strong> <strong>class</strong> <strong>RendererRecyclerViewAdapter</strong> <strong>extends</strong> RecyclerView<strong>.</strong>Adapter <strong>{</strong></pre><pre>        <strong>...</strong><br>	<br>	<strong>@Override</strong><br>	<strong>public</strong> <strong>int</strong> <strong>getItemViewType(final</strong> <strong>int</strong> position<strong>)</strong> <strong>{</strong><br>		<strong>final</strong> ItemModel item <strong>=</strong> getItem<strong>(</strong>position<strong>);</strong><br>		<strong>return</strong> item<strong>.</strong>getType<strong>();</strong><br>	<strong>}</strong></pre><pre>	<strong>private</strong>	ItemModel <strong>getItem(final</strong> <strong>int</strong> position<strong>)</strong> <strong>{</strong><br>		<strong>return</strong> mItems<strong>.</strong>get<strong>(</strong>position<strong>);</strong><br>	<strong>}</strong></pre><pre>        <strong>...</strong><br><strong>}</strong></pre><p>In the meanwhile we’ll improve support of multiple ViewRenderers:</p><pre><strong>public</strong> <strong>class</strong> <strong>RendererRecyclerViewAdapter</strong> <strong>extends</strong> RecyclerView<strong>.</strong>Adapter <strong>{</strong></pre><pre>        <strong>...</strong><br>	<strong>@NonNull</strong><br>	<strong>private</strong> <strong>final</strong> SparseArray<strong>&lt;</strong>ViewRenderer<strong>&gt;</strong> mRenderers <strong>=</strong> <strong>new</strong> SparseArray<strong>&lt;&gt;();</strong></pre><pre>	<strong>@Override</strong><br>	<strong>public</strong> RecyclerView<strong>.</strong>ViewHolder <strong>onCreateViewHolder(final</strong> ViewGroup parent<strong>,</strong> <strong>final</strong> <strong>int</strong> viewType<strong>)</strong> <strong>{</strong><br>		<strong>final</strong> ViewRenderer renderer <strong>=</strong> mRenderers<strong>.</strong>get<strong>(</strong>viewType<strong>);</strong><br>		<strong>if</strong> <strong>(</strong>renderer <strong>!=</strong> <strong>null)</strong> <strong>{</strong><br>			<strong>return</strong> renderer<strong>.</strong>createViewHolder<strong>(</strong>parent<strong>);</strong><br>		<strong>}</strong></pre><pre>		<strong>throw</strong> <strong>new</strong> <strong>RuntimeException(</strong>&quot;Not supported Item View Type: &quot; <strong>+</strong> viewType<strong>);</strong><br>	<strong>}</strong></pre><pre>	<strong>public</strong> <strong>void</strong> <strong>registerRenderer(@NonNull</strong> <strong>final</strong> ViewRenderer renderer<strong>)</strong> <strong>{</strong><br>		<strong>final</strong> <strong>int</strong> type <strong>=</strong> renderer<strong>.</strong>getType<strong>();</strong></pre><pre>		<strong>if</strong> <strong>(</strong>mRenderers<strong>.</strong>get<strong>(</strong>type<strong>)</strong> <strong>==</strong> <strong>null)</strong> <strong>{</strong><br>			mRenderers<strong>.</strong>put<strong>(</strong>type<strong>,</strong> renderer<strong>);</strong><br>		<strong>}</strong> <strong>else</strong> <strong>{</strong><br>			<strong>throw</strong> <strong>new</strong> <strong>RuntimeException(</strong>&quot;ViewRenderer already exist with this type: &quot; <strong>+</strong> type<strong>);</strong><br>		<strong>}</strong><br>	<strong>}</strong></pre><pre>	<strong>@SuppressWarnings(</strong>&quot;unchecked&quot;<strong>)</strong><br>	<strong>@Override</strong><br>	<strong>public</strong> <strong>void</strong> <strong>onBindViewHolder(final</strong> RecyclerView<strong>.</strong>ViewHolder holder<strong>,</strong> <strong>final</strong> <strong>int</strong> position<strong>)</strong> <strong>{</strong><br>		<strong>final</strong> ItemModel item <strong>=</strong> getItem<strong>(</strong>position<strong>);</strong></pre><pre>		<strong>final</strong> ViewRenderer renderer <strong>=</strong> mRenderers<strong>.</strong>get<strong>(</strong>item<strong>.</strong>getType<strong>());</strong><br>		<strong>if</strong> <strong>(</strong>renderer <strong>!=</strong> <strong>null)</strong> <strong>{</strong><br>			renderer<strong>.</strong>bindView<strong>(</strong>item<strong>,</strong> holder<strong>);</strong><br>		<strong>}</strong> <strong>else</strong> <strong>{</strong><br>			<strong>throw</strong> <strong>new</strong> <strong>RuntimeException(</strong>&quot;Not supported View Holder: &quot; <strong>+</strong> holder<strong>);</strong><br>		<strong>}</strong><br>	<strong>}</strong></pre><pre>        <strong>...</strong><br><strong>}</strong></pre><p>As we see, the renderer now has getType() that’s necessary to find the necessary renderer for a specific viewer. Now the adapter is finalized. We implement specific ItemModel, ViewHolder and ViewRenderer classes:</p><pre><strong>public</strong> <strong>class</strong> <strong>SomeModel</strong> <strong>implements</strong> ItemModel <strong>{</strong></pre><pre>    <strong>public</strong> <strong>static</strong> <strong>final</strong> <strong>int</strong> TYPE <strong>=</strong> 0<strong>;</strong><br>    <strong>@NonNull</strong><br>    <strong>private</strong> <strong>final</strong> String mTitle<strong>;</strong></pre><pre>    <strong>public</strong> <strong>SomeModel(@NonNull</strong> <strong>final</strong> String title<strong>)</strong> <strong>{</strong><br>        mTitle <strong>=</strong> title<strong>;</strong><br>    <strong>}</strong></pre><pre>    <strong>@Override</strong><br>    <strong>public</strong> <strong>int</strong> <strong>getType()</strong> <strong>{</strong><br>        <strong>return</strong> TYPE<strong>;</strong><br>    <strong>}</strong></pre><pre>    <strong>@NonNull</strong><br>    <strong>public</strong> String <strong>getTitle()</strong> <strong>{</strong><br>        <strong>return</strong> mTitle<strong>;</strong><br>    <strong>}</strong><br>    <br>    <strong>...</strong></pre><pre><strong>}</strong></pre><pre><strong>public</strong> <strong>class</strong> <strong>SomeViewHolder</strong> <strong>extends</strong> RecyclerView<strong>.</strong>ViewHolder <strong>{</strong></pre><pre>    <strong>public</strong> <strong>final</strong> TextView mTitle<strong>;</strong></pre><pre>    <strong>public</strong> <strong>SomeViewHolder(final</strong> View itemView<strong>)</strong> <strong>{</strong><br>        <strong>super(</strong>itemView<strong>);</strong><br>        mTitle <strong>=</strong> <strong>(</strong>TextView<strong>)</strong> itemView<strong>.</strong>findViewById<strong>(</strong>R<strong>.</strong>id<strong>.</strong>title<strong>);</strong><br>        <strong>...</strong><br>    <strong>}</strong><br><strong>}</strong></pre><pre><strong>public</strong> <strong>class</strong> <strong>SomeViewRenderer</strong> <strong>extends</strong> ViewRenderer<strong>&lt;</strong>SomeModel<strong>,</strong> SomeViewHolder<strong>&gt;</strong> <strong>{</strong></pre><pre>    <strong>public</strong> <strong>SomeViewRenderer(final</strong> <strong>int</strong> type<strong>,</strong> <strong>final</strong> Context context<strong>)</strong> <strong>{</strong><br>        <strong>super(</strong>type<strong>,</strong> context<strong>);</strong><br>    <strong>}</strong></pre><pre>    <strong>@Override</strong> <strong>public</strong><br>    <strong>void</strong> <strong>bindView(@NonNull</strong> <strong>final</strong> SomeModel model<strong>,</strong> <strong>@NonNull</strong> <strong>final</strong> SomeViewHolder holder<strong>)</strong> <strong>{</strong><br>        <strong>...</strong><br>    <strong>}</strong></pre><pre>    <strong>@NonNull</strong><br>    <strong>@Override</strong><br>    <strong>public</strong> SomeViewHolder <strong>createViewHolder(@Nullable</strong> <strong>final</strong> ViewGroup parent<strong>)</strong> <strong>{</strong><br>        <strong>return</strong> <strong>new</strong> <strong>SomeViewHolder(</strong>LayoutInflater<strong>.</strong>from<strong>(</strong>getContext<strong>()).</strong>inflate<strong>(</strong>R<strong>.</strong>layout<strong>.</strong>some_item<strong>,</strong> parent<strong>,</strong> <strong>false));</strong><br>    <strong>}</strong><br><strong>}</strong></pre><p>Now ViewRender has a constructor and two parameters for it: ViewRenderer(int viewType, Context context); I hope there’s no need to explain why we need them. Now we can let our adapter and RecyclerView get to know each other:</p><pre><strong>public</strong> <strong>class</strong> <strong>SomeActivity</strong> <strong>extends</strong> AppCompatActivity <strong>{</strong></pre><pre>    <strong>private</strong> RendererRecyclerViewAdapter mRecyclerViewAdapter<strong>;</strong><br>    <strong>private</strong> RecyclerView mRecyclerView<strong>;</strong></pre><pre>    <strong>@Override</strong><br>    <strong>protected</strong> <strong>void</strong> <strong>onCreate(final</strong> Bundle savedInstanceState<strong>)</strong> <strong>{</strong><br>        <strong>super.</strong>onCreate<strong>(</strong>savedInstanceState<strong>);</strong><br>        setContentView<strong>(</strong>R<strong>.</strong>layout<strong>.</strong>main<strong>);</strong></pre><pre>        mRecyclerViewAdapter <strong>=</strong> <strong>new</strong> RendererRecyclerViewAdapter<strong>();</strong><br>        mRecyclerViewAdapter<strong>.</strong>registerRenderer<strong>(new</strong> SomeViewRenderer<strong>(</strong>SomeModel<strong>.</strong>TYPE<strong>,</strong> <strong>this));</strong><br><em>//        mRecyclerViewAdapter.registerRenderer(...); </em></pre><pre>        mRecyclerView <strong>=</strong> <strong>(</strong>RecyclerView<strong>)</strong> findViewById<strong>(</strong>R<strong>.</strong>id<strong>.</strong>recycler_view<strong>);</strong><br>        mRecyclerView<strong>.</strong>setLayoutManager<strong>(new</strong> LinearLayoutManager<strong>(this));</strong><br>        mRecyclerView<strong>.</strong>setAdapter<strong>(</strong>mRecyclerViewAdapter<strong>);</strong></pre><pre>        mRecyclerViewAdapter<strong>.</strong>setItems<strong>(</strong>getItems<strong>());</strong><br>        mRecyclerViewAdapter<strong>.</strong>notifyDataSetChanged<strong>();</strong><br>    <strong>}</strong></pre><pre>    <strong>...</strong><br><strong>}</strong></pre><h3>Conclusion</h3><p>With relative small effort, we made a working version of the adapter that can be easily used with multiple cell types. All we had to do was implement ViewRenderer for each respective cell type and register it in the adapter.</p><p>By now this implementation has performed well in several large projects.</p><h3>Github Library</h3><p><a href="https://github.com/vivchar/RendererRecyclerViewAdapter">vivchar/RendererRecyclerViewAdapter</a></p><h3>Please read the Part 2</h3><p><a href="https://android.jlelse.eu/easy-handling-of-lists-rendererrecyclerviewadapter-part-2-3b18c8ea6f1b">How to easily add Nested RecyclerView</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfba3979050" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/a-recyclerview-with-multiple-item-types-dfba3979050">A RecyclerView with multiple item types</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>