<?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 Leandro Borges Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Leandro Borges Ferreira on Medium]]></description>
        <link>https://medium.com/@lehen01?source=rss-d7de5f017efe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jnDWq9H_E3Fyho78nWofnw.jpeg</url>
            <title>Stories by Leandro Borges Ferreira on Medium</title>
            <link>https://medium.com/@lehen01?source=rss-d7de5f017efe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 21:25:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lehen01/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[Compose Multiplatform: Quickly develop a feature-rich text editor.]]></title>
            <link>https://medium.com/@lehen01/compose-multiplatform-quickly-develop-a-feature-rich-text-editor-6352687a8741?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6352687a8741</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 09:52:50 GMT</pubDate>
            <atom:updated>2025-07-19T09:52:50.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*whJGjM_2AfPgPjErhe9I0w.png" /></figure><p>Some applications may need more than a simple text box for text editing. Apps like Slack may need bold, italic, underline and many more features. In the canvas feature, you can drag and drop parts of the text, both inside and outside the app. You can add images, audio, video… and many more!</p><p>Creating a rich text editor is not an easy task. You can&#39;t simply ask ChatGPT, and then it provides you with all the code… Many interactions are necessary.</p><p>But today, we are going to create an amazing text editor using <a href="https://docs.writeopia.io/docs/sdk/overview">writeopia-sdk</a>. This is an open-source project, and you can check the code here: <a href="https://github.com/Writeopia/Writeopia">https://github.com/Writeopia/Writeopia</a>.</p><p>You can use this SDK to create editors for iOS, Android, Web and desktop apps! This is a Compose Multiplatform project, and it fits all the possible apps. The editor self-adapts accordingly to the platform that you&#39;re using.</p><p>So, let&#39;s start? Here comes chapter 1!</p><h3>Chapter 1— Adding the dependencies</h3><p>Okay, so the boring part. We need to add the necessary dependencies. Writeopia is made with a modular approach. You don&#39;t need to add dependencies that you don&#39;t want. You can add persistence, serialization, exporting, importing, etc. There are many possibilities, but let&#39;s start with something simple in this tutorial.</p><p>Add basic dependencies in your build.gradle.kts:</p><pre>implementation(libs.writeopia.models)<br>implementation(libs.writeopia.core)<br>implementation(libs.writeopia.ui)</pre><p>And in your toml file:</p><pre>[versions]<br>writeopia = &quot;0.11.1&quot;<br><br>[libraries]<br>writeopia-core = { module = &quot;io.writeopia:writeopia-core&quot;, version.ref = &quot;writeopia&quot; }<br>writeopia-models = { module = &quot;io.writeopia:writeopia-models&quot;, version.ref = &quot;writeopia&quot; }<br>writeopia-ui = { module = &quot;io.writeopia:writeopia-ui&quot;, version.ref = &quot;writeopia&quot; }</pre><p>The version may vary. Check the latest version of the project.</p><p>Sync your files, and now let&#39;s move. Next chapter!</p><h3>Chapter 2 — Configuring the library</h3><p>To make the library work. We need 2 classes: <strong>WriteopiaStateManager </strong>and <strong>WriteopiaEditor. </strong>So, first, create a simple our state manager:</p><pre>@Composable<br>fun Editor(modifier: Modifier = Modifier) {<br>    val stateManager = remember { // 1 -&gt; Use &quot;remember&quot;, so you don&#39;t create it many times<br>        WriteopiaStateManager.create( // 2-&gt; Create the class<br>            WriteopiaManager(),<br>            dispatcher = Dispatchers.IO,<br>        ).also {<br>            it.newDocument(&quot;documentId&quot;) // 3-&gt; Create a new document. <br>        }<br>    }<br><br>    // 4 -&gt; Collect the state. It will change as the user writes.<br>    val drawState by stateManager.toDraw.collectAsState(DrawState()) <br>}</pre><p>Now, let&#39;s create our editor:</p><pre>@Composable<br>fun Editor(modifier: Modifier = Modifier) {<br>    val stateManager = remember {<br>        WriteopiaStateManager.create(<br>            WriteopiaManager(),<br>            dispatcher = Dispatchers.IO,<br>        ).also {<br>            it.newDocument(&quot;documentId&quot;)<br>        }<br>    }<br><br>    val drawState by stateManager.toDraw.collectAsState(DrawState())<br><br>    WriteopiaEditor(<br>        modifier = modifier.fillMaxSize(),<br>        storyState = drawState,<br>        // You need to create the drawers for each type of information<br>        // You can substitue drawers too. <br>        drawers = DefaultDrawersAndroid.create(manager = stateManager) <br>    )<br>}</pre><p>Okay. Now add this to your app, it should be something like this:</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            EditorSampleTheme {<br>                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding -&gt;<br>                    Editor(<br>                        modifier = Modifier.padding(innerPadding)<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Now, compile the project. Don&#39;t worry, I&#39;ll wait… any second now… just a bit more… ok, it is done, right?</p><p>You should see something like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1102567997%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1102567997&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2038340724-cb786326deeab1ac4d3273490b2441ac155b8678f3fe3ebe32dfaa8086290bf0-d_295x166%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="432" height="446" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b96b5c007b8f4fe5cda4999d5f4afef/href">https://medium.com/media/5b96b5c007b8f4fe5cda4999d5f4afef/href</a></iframe><p>Yes!! It works!! Yes… There&#39;s a typo, I know. Now you probably would like to add more stuff, right? Let&#39;s do that. Next chapter!</p><h3>Chapter 3 — Adding new features</h3><p>So what are we going to do? Oh, right, bold, italic and underline, the classic stuff. Okay, we can do that.</p><p>You see, the SDK comes with many functions that you can use to expand the text editor. You can use create buttons that trigger those functions and create your very particular UX. I&#39;m curious to see how other devs and editors will look like. Anyway, let’s update the code to add buttons that style the text.</p><pre>@Composable<br>fun Editor(modifier: Modifier = Modifier) {<br>    val stateManager = remember {<br>        WriteopiaStateManager.create(<br>            WriteopiaManager(),<br>            dispatcher = Dispatchers.IO,<br>        ).also {<br>            it.newDocument(&quot;documentId&quot;)<br>        }<br>    }<br><br>    val drawState by stateManager.toDraw.collectAsState(DrawState())<br><br>    Box {<br>        WriteopiaEditor(<br>            modifier = modifier.fillMaxSize(),<br>            storyState = drawState,<br>            drawers = DefaultDrawersAndroid.create(manager = stateManager)<br>        )<br><br>        Row(modifier = Modifier<br>            .align(Alignment.BottomCenter)<br>            .padding(bottom = 50.dp)) {<br>            Text(<br>                &quot;B&quot;,<br>                fontSize = 20.sp,<br>                modifier = Modifier.clickable {<br>                    stateManager.toggleSpan(Span.BOLD)<br>                }.padding(10.dp)<br>            )<br><br>            Spacer(modifier = Modifier.width(8.dp))<br><br>            Text(<br>                &quot;I&quot;,<br>                fontSize = 20.sp,<br>                modifier = Modifier.clickable {<br>                    stateManager.toggleSpan(Span.ITALIC)<br>                }.padding(10.dp)<br>            )<br><br>            Spacer(modifier = Modifier.width(8.dp))<br><br>            Text(<br>                &quot;U&quot;,<br>                fontSize = 20.sp,<br>                modifier = Modifier.clickable {<br>                    stateManager.toggleSpan(Span.UNDERLINE)<br>                }.padding(10.dp)<br>            )<br>        }<br>    }<br>}</pre><p>You should see &quot;B&quot;, &quot;I&quot; and &quot;U&quot; buttons at the bottom of the editor. When you select a piece of text and click on the &quot;B&quot;, it should change the text to bold like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*WGDdc59zvEH5XIql8HvAGA.png" /></figure><p>You can also select multiple lines (by swiping the line) and add bold to multiple lines. Cool right?</p><p>You can call many more methods to stream AI text, adding images, copy/cut selected lines, etc. You can change the <strong>DefaultDrawersAndroid </strong>that you used in the code before to change the way the editor looks. You can also create different drawers for each type of information and change the UX completely. Read more about it in the <a href="https://docs.writeopia.io/docs/sdk/overview">documentation</a> of the project.</p><p>If you would like to see an app with many features on top of the SDK, you can download the Writeopia app and check what it can do. Here is our website: <a href="https://writeopia.io/">https://writeopia.io/</a></p><h3>Chapter 4 — Further extending the SDK</h3><p>There are many examples of things that can be done with this SDK.</p><ul><li>Blog editor</li><li>Jornal app</li><li>Email editing</li><li>Canvas for AI</li><li>Enhanced text editor for chat apps</li></ul><p>Specific examples are hard to cover because there are so many. If there a specific thing that you would like to know how to do? Maybe generate text like ChatGPT does? If you&#39;re interested in something, put it in the comments, so I can cover it.</p><p>Now, let’s conclude this article.</p><h3>Chapter 5 — Thank you!</h3><p>Thank you for reading this until the end. If you think the project is interesting, don&#39;t forget to star it! No, seriously, do it. I can wait… did you do it? Okay, then have a good day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6352687a8741" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Writeopia: Open Source text editor!]]></title>
            <link>https://medium.com/@lehen01/introducing-writeopia-open-source-text-editor-7ebcb4c67974?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ebcb4c67974</guid>
            <category><![CDATA[knowledge-management]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 10:22:22 GMT</pubDate>
            <atom:updated>2025-07-06T10:22:22.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing Writeopia: Open Source AI text editor!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wzWhec1D089ouQvkRPyzg.png" /></figure><p>Hello world. I want to share a project with all of you.</p><p>Some time ago, I decided to create my open-source text editor, Writeopia.</p><blockquote>Note. Our website: <a href="https://writeopia.io/">https://writeopia.io/</a>.</blockquote><p>It should have a simple goal: Give users the power of choice. Most editors felt too limiting; you&#39;re forced to send your data to a private cloud, without much control over your data. If you want to use AI to help fix some parts of the content or generate parts of it, it doesn&#39;t allow you to choose the provider.</p><p>So I created <strong>Writeopia: </strong>a clean, focused, and privacy-first text editor that puts you in control. It works completely offline, keeps your writing safe and local, and gives you the freedom to organise your notes and documents the way you want. It integrates with Ollama for local AI, so you can choose to use all the open-source models available.</p><p>It provides you with a place where you control where your data goes.</p><p><strong>We are living in an AI revolution, that&#39;s a fact. But instead of creating new tools that everybody can participate in and benefit from, I see the big companies increasing their dominance even more. Everything goes through an LLM and gets synced to a server without our choice. Our thoughts are never private.</strong></p><h3>We’re building Writeopia because we truly believe privacy matters, and it’s up to us, not anyone else, to decide where our data goes.</h3><p>We designed our text editor with some key principles that we believe are non negotiable:</p><h4>Bring Your Own AI</h4><p>Writeopia lets you <strong>plug in any AI provider</strong>. You choose the model. You can use Deepseek, Mistral, Gemma…</p><h4>No lock-in</h4><p>You can easily export your entire workspace and sync it however you like with Google Drive, GitHub, your own cloud storage, and more. The app makes syncing your files simple and flexible.</p><h4>Offline-First</h4><p>Writeopia works seamlessly <strong>without an internet connection</strong>. Everything you write is stored locally. Your notes are yours. This isn’t just a feature — it’s a philosophy.</p><h4>Local-First, Global Collaboration</h4><p>Coming soon: real-time collaboration with <strong>peer-to-peer syncing</strong>. You can deploy the service on your infrastructure and control how your documents are managed.</p><h4><strong>Open Source</strong></h4><p>Writeopia is built with transparency and trust at its core. The entire app is open source, so you can inspect the code, contribute features, or even fork it to create your version. Tools for thinking and creativity should be auditable, community-driven, and built to last, not controlled by a single company. You can see the code of the project at: <a href="https://github.com/Writeopia/Writeopia">https://github.com/Writeopia/Writeopia</a></p><p>The journey so far has been very interesting. Many users shared their point of view about how they would like to see it grow, what they like and, well, what they don&#39;t. All of this feedback has been valuable in helping us understand how we can improve and, more importantly, which direction people want us to go.</p><p>Software shouldn’t lock you into a SaaS that holds your data hostage or charges you just to access what’s yours. It shouldn’t force you into one cloud provider and it should never be owned by just a few people.</p><p>Writeopia is still growing, and we’re building it together, with you. If you believe software should be open, flexible, and respect your freedom, we’d love for you to join us on this journey. Let’s shape a better future for creative tools.</p><p>In future articles, I’ll dive deeper into how Writeopia works under the hood covering the SDK, how the text editor was built, and sharing more updates as the project evolves. Stay tuned!</p><p><strong>If you like the project, don&#39;t forget to give us a star. </strong>⭐️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ebcb4c67974" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradle modules: Running unit tests only in affected modules]]></title>
            <link>https://itnext.io/gradle-modules-running-unit-tests-only-in-affected-modules-fff89562339e?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/fff89562339e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 10:01:05 GMT</pubDate>
            <atom:updated>2020-09-03T19:33:13.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CnZspxEAwgw-SfkRONTFhQ.jpeg" /></figure><h3>1 — Intro</h3><p>Hi.</p><p>Multimodular projects are becoming more popular in the Android world, especially after Google IO of 2019, where Google introduced this idea and showed the benefits of it.</p><p>Although modules are becoming more popular, there&#39;s still a lot to be done in the tooling to analyse and deal with then. It is hard to find tools to analyse how good is the distribution of code between the modules, how the compilation is made faster by the then, visualize the dependencies between modules and to look for possible optimizations.</p><p>So, in this article, I would like to teach you how to make an interesting project to help you to analyse your modular Gradle project (It is important to say that it applies to any Gradle project, this is not limited to android at all). The goal is to:</p><p>1- Print the affected modules by a branch.</p><p>2- Run unit tests only in the affected modules.</p><p>3- Run UI tests on in the affected modules. (This comes in a future article)</p><p>4- Visualize the graph of dependencies and study how the related to each other. (This also comes on a future article)</p><p>This can help you and your team to avoid running unit tests on modules that were not changed by a PR and speed up your CI, understand how the modules interact with each other and how complex this graph is at the moment. But enough with this introduction, let&#39;s have some fun!</p><h3>2 — Finding the affected modules</h3><p>For this problem, I created a Gradle plugin that you can use and print the adjacency list of your modules (By the way, if you don&#39;t know what an adjacency list is: Is it a way to represent a graph, you can search for it and there will be a lot of references). You can find the documentation and the code for the plugin here: <a href="https://github.com/leandroBorgesFerreira/dag-command">https://github.com/leandroBorgesFerreira/dag-command</a>. It is based on the amazing work of <a href="https://github.com/hpedrorodrigues"><strong>Pedro Rodriguez</strong></a><strong>.</strong></p><p>Let&#39;s suppose that we have a modular app, like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*o13pbg7Hzt8nxD_rPDWAhA.png" /><figcaption>Image 1 — Example of module app.</figcaption></figure><p>You can take a look at the small project here: <a href="https://github.com/leandroBorgesFerreira/FoodList">https://github.com/leandroBorgesFerreira/FoodList</a></p><p>So, 6 modules and they have some dependency between each other, we will understand how they depend on each other later in this article.</p><p>You can add the library in this way. The library in the project level Gradle file.</p><p><strong>build.gradle.kts (Kotlin version):</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85f94d8764d5dbcdb5c22a004b302ccc/href">https://medium.com/media/85f94d8764d5dbcdb5c22a004b302ccc/href</a></iframe><p><strong>build.gradle (Groovy version):</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e881ee477409ae1e9df96a563683e0c/href">https://medium.com/media/6e881ee477409ae1e9df96a563683e0c/href</a></iframe><p>Then you can make a small change (just change any line of the code, like adding a comment) in the <strong>core</strong> module and I run the plugin:</p><pre>./gradlew dag-command</pre><p>You can go to the folder <strong>./build/dag-command/ </strong>and you&#39;ll see some files. There you&#39;ll find <strong>adjacencies-list.json. </strong>This file contains information about the graph of dependencies of the modules of your app. In the case of the Image 1 example, this is the output that I got:</p><pre>{“app”:[],”core”:[“showfood”],”data”:[“app”,”showfood”],”domain”:[“data”,”showfood”],”search”:[“showfood”],”showfood”:[“app”]}</pre><p>which can be formatted to:</p><pre>{<br>  &quot;app&quot;: [],<br>  &quot;core&quot;: [<br>    &quot;showfood&quot;<br>  ],<br>  &quot;data&quot;: [<br>    &quot;app&quot;,<br>    &quot;showfood&quot;<br>  ],<br>  &quot;domain&quot;: [<br>    &quot;data&quot;,<br>    &quot;showfood&quot;<br>  ],<br>  &quot;search&quot;: [<br>    &quot;showfood&quot;<br>  ],<br>  &quot;showfood&quot;: [<br>    &quot;app&quot;<br>  ]<br>}</pre><p>And you can see the affected modules by looking in the file <strong>affected-modules.json</strong>. That&#39;s my output:</p><pre>[&quot;app&quot;,&quot;core&quot;,&quot;showfood&quot;]</pre><p>You can take a look at the adjacency list and conclude that changing the <strong>core </strong>will affect <strong>app, showfood </strong>and<strong> core</strong> because the dependency is <strong>core</strong> -&gt; <strong>showfood</strong> -&gt; <strong>app</strong>.</p><p>Ok. So we made it! Now we know how to create the affected modules by our PR! But… that&#39;s not very useful… right? We need to use this information to create something more, like speed up our tests or analyse how our modules are connected (the later will come in another article, sorry =P). This leads us to the next part of the article.</p><h3>3 — Running unit tests only for changed modules</h3><p>What we need to do now is to create a command that will run the unit tests only for the modules that were changed by the current branch.</p><p>I use Python for my day to day automation, but you can use any language that you prefer. You can parse the affected modules to a simple command with not much trouble:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2816209287a93859330b5562a9800482/href">https://medium.com/media/2816209287a93859330b5562a9800482/href</a></iframe><p>This snippet will produce this Gradle command:</p><pre>./gradlew core:testDebug showfood:testDebug app:testDebug</pre><p>So the modules <strong>data,</strong> <strong>domain </strong>and <strong>search </strong>are not tested because our change did not affect then, so running unit tests on those modules would be just a waste of time.</p><h3>4 — I hope you enjoyed it =]</h3><p>Now you can enjoy some extra time on your CI. Maybe you can drink one extra cup of coffee, have some conversation with your colleagues, read a small part of a book… you name it!</p><p>If this article and the library helped you somehow (or if you think this is an interesting text) please remember to click that clap button and give me a little star on Github. That helps a lot!</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fff89562339e" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/gradle-modules-running-unit-tests-only-in-affected-modules-fff89562339e">Gradle modules: Running unit tests only in affected modules</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrow 101 — How Higher order types can be amazing]]></title>
            <link>https://medium.com/@lehen01/arrow-101-how-higher-order-types-can-be-amazing-38d0c7c19344?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/38d0c7c19344</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[category-theory]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 20:22:18 GMT</pubDate>
            <atom:updated>2018-12-19T18:58:34.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arrow 101 — How Higher order types can be amazing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*r3fzPAFyoyBM3zQYi3Grmw.png" /></figure><p>This article explains how to create an Android app using higher order types and how to switch between RxJava to Coroutines with one line by abstracting away to technology chosen in your application.</p><p>The code for the article can be found in <a href="https://github.com/leandroBorgesFerreira/ArrowTaglessFinal">this repository</a>.</p><h3>1 — Intro</h3><p>So Kotlin doesn&#39;t have Higher order types =|. But don&#39;t feel bad about it, because you can use Arrow to emulate then! Uhuu! Although you cannot have a syntax like this one:</p><pre>F&lt;A&gt;</pre><p>You can emulate it with a syntax like this:</p><pre>Kind&lt;F, A&gt; // you have Kind&lt;F, A&gt; = F&lt;A&gt;</pre><p>And you can take advantage of a much more powerful type system. It can be really useful to build a DSL where you don&#39;t need to choose the wrapper for your data until the very last moment. This can be very useful to change technologies if you decide to in a latter moment. If you&#39;re not sure about using RxJava or Coroutines, for example, not to worry, you can change it with just a single line of code.</p><p>If you are more interested about how the Kind of Arrow works, you can take a look a this presentation: <a href="https://www.youtube.com/watch?v=ERM0mBPNLHc">https://www.youtube.com/watch?v=ERM0mBPNLHc</a></p><h3>2 — The project</h3><p>We are going to create an app that looks a lot like the one from <a href="https://medium.com/@lehen01/arrow-101-building-an-android-app-using-functional-programming-fe959675d96d">this article</a>. if you didn&#39;t read it, that&#39;s fine, I&#39;ll explain. It is an app that shows the repositories of Java in the Github. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*BBPhjvHdmGv9TE2lhGxJZQ.png" /></figure><p>And that&#39;s it. Just one screen. Pretty simple, right?</p><p>The app is made using MVP, because it is a simple and easy to follow architecture. So, shall we start?</p><h3>2 — The presentation layer</h3><p>That&#39;s the code of our presenter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e4e657dc702346246f9c64008a8e576/href">https://medium.com/media/4e4e657dc702346246f9c64008a8e576/href</a></iframe><p>So, what&#39;s the first parameter of this constructor? <strong>MonadDefer</strong>?</p><p><strong>MonadDefer </strong>is a type of monad capable of deferring the computation, so you can run it in a later moment. We use it to create our Monad Comprehension with <strong><em>bindingCancellable</em>. </strong>It returns the <strong>Kind</strong> that we are hopping to get and also a <strong>Disposable</strong> instance. We you can <strong><em>invoke </em></strong>in the disposable and the value binded (<strong>kind </strong>in this example) is lifted to <strong><em>BindingCancellationException, </em></strong>so<strong><em> </em></strong>the action doesn&#39;t complete. We invoke all disposables in a method in our presenter that should be called in the <strong><em>onPause()</em></strong> moment of the activity&#39;s lifecycle.</p><p>So what Monad are we going to use? It doesn&#39;t matter! It could be an Observable, Single or an IO using Coroutines, but his will concretised in a later moment. For now, all we care is that we call our Use Case and we bind the result to <strong>kind</strong>. So let&#39;s go to our model layer.</p><h3>3 — Model Layer</h3><p>Arrow has a integration module with Retrofit, available prior the version 0.8.0. We are going to use this module to simplify our code. First we need to add it in our project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2dae0bfdeeb472b628aa11f9236b039/href">https://medium.com/media/a2dae0bfdeeb472b628aa11f9236b039/href</a></iframe><p>Then we can create our endpoints requesting CallK as the return type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b56109628a33d044eb47a61c933a409/href">https://medium.com/media/7b56109628a33d044eb47a61c933a409/href</a></iframe><p>CallK offers a way to run the OkHttp requests and return the response wrapped inside a a given Monad. I&#39;ll a show an example of use in the 4.2 section. Let&#39;s move on for now.</p><h3>3.1 — Use Case</h3><p>Very simple class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3575601cd69dab1e06f6cb546d3a42b0/href">https://medium.com/media/3575601cd69dab1e06f6cb546d3a42b0/href</a></iframe><p>Ok. We just called our dataSource. So let&#39;s go there.</p><h3>3.2— DataSource</h3><p>All we have is a comprehension and a call to our apiClient.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0c5a89226a65fe5b9cdec9a6b4a4ef/href">https://medium.com/media/5b0c5a89226a65fe5b9cdec9a6b4a4ef/href</a></iframe><p>After we use async we get a <strong>Response</strong> from <strong>CallK</strong>. <strong>Response</strong> has already a extension function to unwrap the body in a monadic way.</p><h3><strong>4 — The Activity</strong></h3><p>After we create our structure in a Monadic way. All we need to do is to provide a Monad to run our logic.</p><p>So that&#39;s what I have in my Activity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/454583513fd848946eec311f86d42964/href">https://medium.com/media/454583513fd848946eec311f86d42964/href</a></iframe><p>So now we concretised our implementation to RxJava using the integration of Arrow. But one thing really nice about our approach is that we can change our monad with just one command. If we no longer want to use RxJava, that’s ok. Just change the monad being used and that’s it. Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c30f7b0291a608a54261af22077c693/href">https://medium.com/media/9c30f7b0291a608a54261af22077c693/href</a></iframe><p>And we have the same results. Here&#39;s what I got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*_8olM9n_qwtw4Vx9C9VeBw.png" /></figure><p>You can use this same approach to work with so many other cases like building a framework, a DSL a command line user interface… You decide, just keep in mind that with this approach you can let the choose for a specific type to a later moment and create code that is a lot easier to change and adapt.</p><h3>5 — Bonus: Using delegation to improve the code.</h3><p>So a interesting improvement that can be done in our code is to use our components as Monad an avoid using our Async&lt;F&gt; dependencies every where.</p><p>This can be done with delegation. I will let the code of the improvement so you can use it as an example for you next Arrow project.</p><p><strong>Presenter:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d99dcd0324dc9ecaefb26642456df2a2/href">https://medium.com/media/d99dcd0324dc9ecaefb26642456df2a2/href</a></iframe><p><strong>Use case:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9960f1096648fd6570e90f87e84772db/href">https://medium.com/media/9960f1096648fd6570e90f87e84772db/href</a></iframe><p><strong>Data source:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbab21f2ca5e45739856925ee9fbc167/href">https://medium.com/media/dbab21f2ca5e45739856925ee9fbc167/href</a></iframe><p>So that&#39;s it!</p><p>I hope you enjoyed the article!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38d0c7c19344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrow 101 - Modelling a real world problem with Semigroups]]></title>
            <link>https://medium.com/@lehen01/arrow-101-modelling-a-real-world-problem-with-semigroups-d8f22cdf54c?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f22cdf54c</guid>
            <category><![CDATA[category-theory]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 19:20:28 GMT</pubDate>
            <atom:updated>2018-08-15T19:25:49.098Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arrow 101 — Modelling a real world problem with Semigroups</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsd31hM-Q12PKdr7atlybQ.png" /></figure><h3>1 — Intro</h3><p>FP offers us many tools to create more terse and less imperative code. But besides knowing how to use then, it is also important to learn to see our problems in a mathematical way.</p><p>In the article I will present how to use a tool from Category Theory to model a simple, yet real scenario: <strong>Semigroups</strong>. You don&#39;t need to be a super theoretical programer or be a master of calculus. This concept is easy, it just have some weird name.</p><p>I hope you enjoy it and give it a try!</p><p>If you would like to access a github repository with all the code, look here: <a href="https://github.com/leandroBorgesFerreira/ArrowModel">https://github.com/leandroBorgesFerreira/ArrowModel</a></p><h3>2 — The Problem</h3><p>Let&#39;s suppose we work for a fintech called PurpleBank. It has many financial services and it is growing their number. At some point, the company decides to offer virtual credit cards for the costumers, so they can buy online in a more secure way.</p><p>A virtual card can be deleted, but you cannot simply make the <strong>charges</strong> in that card disappear. You need to transfer all the charges to another card right before deleting it. The credit limit for the old card should also go to the other card, since each card was its own limit. <em>So the old card will be </em><strong><em>combined </em></strong><em>to another one.</em></p><p>Like this:</p><p><strong>Card1</strong></p><p>— Charge 1, Charge 2; Limit $400</p><p><strong>Card2</strong></p><p>— Charge 3, Charge 4; Limit $800</p><p><strong>After deleting Card1</strong>, we just have Card2:</p><p><strong>Card2</strong></p><p>— Charge 1, Charge 2, Charge 3, Charge 4; Limit $1200</p><p>The user should also be able to pay for each card bill individually or pay for all of then at once. <em>So virtual card can be </em><strong><em>transformed</em></strong><em> into Bills. Bills also can be </em><strong><em>combined</em></strong><em>.</em></p><p>So, there&#39;s a tool that can help us to solve this problem, <strong>Semigroups.</strong></p><h3>2.1 — Virtual Cards and Bills as Semigroups</h3><p>I&#39;m not going to give you an explanation about what is a <strong>Semigroup</strong>. You can find some resources about it over the internet. <a href="https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/">Category Theory for Programmers</a> and <a href="https://www.47deg.com/blog/science-behind-functional-programming/">this article</a> are some good sources, take a look and you will get it =]</p><p>So, a <strong>Semigroup</strong> should be combinable, right? Like numbers, you can combine then by adding: 3 + 2 = 5. String are easy to see it too: &quot;Cheers from &quot; + &quot;Brazil&quot; = &quot;Cheers from Brazil&quot;. But… uhm… Virtual Card are not so obvious, right? Let&#39;s take a look of what would be a data class for a VirtualCard:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a34abe35633fed94528f0fe41c56c88/href">https://medium.com/media/6a34abe35633fed94528f0fe41c56c88/href</a></iframe><p>The only obvious part to sum here is the chargeList, all we have to do is to concatenate to another list.</p><p>But the chargeList is the only part that we actually would like to keep. We will sum one card to another one, so we need to keep the data of one of the two cards and keep all the charges from both, the rest will be deleted.</p><p>So we have this Semigroup for VirtualCard:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac2e5a9c9858092b9a19ec6a49ae7be4/href">https://medium.com/media/ac2e5a9c9858092b9a19ec6a49ae7be4/href</a></iframe><p>We keep the data of the first card and combine the charges of the two. Easy, right?</p><p>The same goes for Bills:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c95429a3a71417eac5c81a7155e8d869/href">https://medium.com/media/c95429a3a71417eac5c81a7155e8d869/href</a></iframe><p>So now we have our Semigroups. If we need to sum then, we can use the combineAll method. Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/128f09c0efc010dd0982bc00e6448a55/href">https://medium.com/media/128f09c0efc010dd0982bc00e6448a55/href</a></iframe><p>But you might be thinking: “Wait, so we have this:”</p><pre>virtualCard1 + virtualCard2 ≠ virtualCard2 + virtualCard1</pre><p>“Is it right? If we invert the order of the sum, we change the result, that’s weird”</p><p>Actually, it is right.</p><p>We don’t need the <strong>commutative property</strong>. As long we have <strong>associative</strong> <strong>property</strong>, it is a <strong>Semigroup</strong>. So we are good to go. Just remember that the order matters in this sum and that’s probably what you’ll see in real case scenarios. It our example the virtualCard2 must be the one that is going to be deleted.</p><p>Arrow provides a library to tests if you correctly implemented your code respecting the concept of Category Theory that you can using (In this example, Semigroup).</p><p>You can include the library of Arrow tests like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89808d9a7e84905926ee6f34ada9d77e/href">https://medium.com/media/89808d9a7e84905926ee6f34ada9d77e/href</a></iframe><p>And then you can test your Semigroups. Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5de6017488c824fdc3c5899b6e4fdcab/href">https://medium.com/media/5de6017488c824fdc3c5899b6e4fdcab/href</a></iframe><p>SemigroupLaws are going to verify that the Semigroup create by you follow the rules of a Semigroup, so you can securely use it in your program. This Laws is going if you are respecting the <strong>associative property</strong>:</p><pre>(SemiG1 + SemiG2) + SemiG3 = SemiG1 + (SemiG2 + SemiG3)</pre><pre>//Also</pre><pre>This is the same relation as:</pre><pre>(1 + 2) + 3 = 1 + (2 + 3) = 6</pre><pre>//or</pre><pre>(&quot;Cheer&#39;s &quot; + &quot;from &quot;) + &quot;Brazil&quot; = <br>&quot;Cheer&#39;s &quot; + (&quot;from &quot; + &quot;Brazil&quot;)<br>= &quot;Cheer&#39;s from Brazil&quot;</pre><h3>3— Modelling our &quot;database&quot;</h3><p>Now we know enough to solve our problem. Before going further, let me show how I am modeling our Charge:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ac7d59ce67a34d56591dab0857ebe73/href">https://medium.com/media/0ac7d59ce67a34d56591dab0857ebe73/href</a></iframe><p>A very simple class. To work with our Entities we need a class to represent our database. A simple interface could be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62ed6e1cc4d2bc4d03c16e9affaab24/href">https://medium.com/media/e62ed6e1cc4d2bc4d03c16e9affaab24/href</a></iframe><p>And a simple implementation could be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f8777c8060954b4494a1efa2990325/href">https://medium.com/media/00f8777c8060954b4494a1efa2990325/href</a></iframe><p>So that&#39;s our database DAO. That&#39;s not our focus for now, so let&#39;s move along.</p><h3>4 — Solving the problem</h3><h3>4.1 — Virtual Cards</h3><p>Before deleting our old card, we need to fuse it with an existing card. We also need to guarantee that our computation only runs if both IDs passed to us are valid. So we have this logic to merge two cards and end up with only one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68b02f6b8b27eef0bcc1c481be8cf729/href">https://medium.com/media/68b02f6b8b27eef0bcc1c481be8cf729/href</a></iframe><p>We use <strong>Monad Comprehensions, Applicative Builder </strong>and<strong> </strong>a <strong>map.</strong></p><p>Monad Comprehensions is feature available in many languages. It makes possible to write sequential actions in a way what feels natural and easy to read. You can check about it <a href="https://arrow-kt.io/docs/patterns/monad_comprehensions/">here</a>.</p><p>The <strong>Applicative Builder </strong>receives all our <strong>Options</strong> and create a new one in a Tuple with all the values passed to it. This way, the will only run the <strong>map </strong>method if both options have a value. If any of the two have <strong>None </strong>as value, the resulting Option will have None as result and our <strong>map </strong>will be circuit breaked.</p><p>After this, we combine the cards in our <strong>map</strong>, save the combined card and then delete the old one.</p><p>This way, we are able to deal with our virtual cards as a Semigroup, we can combine than to create a delete logic. This code will get more interesting latter when we improve this code. For now, let&#39;s take a look in our Bills.</p><h3>4.2 — Bills</h3><p>Our card got deleted and combined with another card. So, time to pay the Bill.</p><p>To create a total Bill, all we have to do is to map our VirtualCard to the Bill that it represents. Take a look at the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1722b9a29ecfcf6a386d45f9272567f4/href">https://medium.com/media/1722b9a29ecfcf6a386d45f9272567f4/href</a></iframe><p>We morph our VirtualCards to Bills, then, as Bill are also Semigroups, we combine then into a single Bill. We can call this method like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/447ccb8acd884257fb117984cfa5ad79/href">https://medium.com/media/447ccb8acd884257fb117984cfa5ad79/href</a></iframe><p>And that&#39;s it. With <strong>Semigroups</strong> we can model many problems to morphisms and combinations of our data. Bills, for example, could have the same behaviour of VirtualCards. Maybe you have Bills that you would like to pay every month, but you would to pay then all at once (or some of then at once) and gain a discount. So the idea of merging information can be used for more than just virtual cards. Perhaps we can extend our code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a23e9391831db3b98be6bd6e4ecc2f/href">https://medium.com/media/d8a23e9391831db3b98be6bd6e4ecc2f/href</a></iframe><p>Now we have a small DSL. This piece of code could be used to Virtual Cards, Bills and any other Entity that has the same logic of <strong><em>combine before delete</em></strong><em>.</em> This way we can create building blocks that are going to be used in our whole system and Arrow can help us to create a nice abstract and concise code.</p><p>The code doesn&#39;t look bad by now, but there&#39;s a little problem with our DSL: Our functions are not pure. The function <strong>mergeEntity</strong> is causing a side effect and this should be avoided. Our computation could be deferred and the write in our database could happen only in a layer that side effects are acceptable. So let&#39;s keep working.</p><h3>5 — Improving the code</h3><p>Let&#39;s create an interface for our DAO with deferred computation. First, we need a Monad capable of deferring our computation (You can look <a href="https://arrow-kt.io/docs/patterns/monads/">here</a> for a tutorial about Monads). Second, we need to define a return type that changes accordingly to the Monad chosen. Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50755a9ffe4140e59fb3256655b9a731/href">https://medium.com/media/50755a9ffe4140e59fb3256655b9a731/href</a></iframe><p><strong>MonadDefer</strong> can be any kind Monad capable of defering our computation, it can be <strong>IO </strong>or an <strong>ObservableK </strong>(from RxJava integration) and <strong>Kind</strong> is a <strong>Higher Kinded Type</strong> (take a look <a href="https://arrow-kt.io/docs/patterns/glossary/#higher-kinds">here</a> for a tutorial), it is translated to F&lt;List&lt;T&gt;&gt; or F&lt;Option&lt;T&gt;&gt;. This code will be concretised as the type of our MonadDefer latter on.</p><p>So basically our functions are saying: &quot;Give me a certain class capable to postpone some behaviour and I will return you some data based on what you offered me&quot;. It seams fair.</p><p>So we can have an actual class for our interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc5f039eae9ca70ea8bce00bcb1fd4ab/href">https://medium.com/media/bc5f039eae9ca70ea8bce00bcb1fd4ab/href</a></iframe><p>All this class does is to apply the <strong>MonadDefer</strong> on the EntityDAO. That&#39;s it, the same behaviour, but inside a different container. To use this new DAO, we need to change our <strong><em>mergeEntity </em></strong>functionThis. So now we have this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd8d33df696fd27111e0eac2397cfcf/href">https://medium.com/media/dfd8d33df696fd27111e0eac2397cfcf/href</a></iframe><p>Ok… The code looks different. Let&#39;s go step by step. First, we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe71135d6a21692600d89b253bff011/href">https://medium.com/media/7fe71135d6a21692600d89b253bff011/href</a></iframe><p>Now we receive our <strong>DeferredEntityDAO </strong>and a <strong>MonadDefer</strong>. By passing in a MonadDefer we will be able to concretise our implementation, this is why it is needed. Then we use monad comprehensions to <em>bind </em>our values and make our code look like imperative code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a28976e0c029471d5ecc9d31ab2b3f1/href">https://medium.com/media/2a28976e0c029471d5ecc9d31ab2b3f1/href</a></iframe><p>Lastly, we combine our entities, save the combination and than delete the old card.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ba5003fa6d8d2fffe7cbeedc4164367/href">https://medium.com/media/0ba5003fa6d8d2fffe7cbeedc4164367/href</a></iframe><p>But our computation was never run, because everything is being deferred. We need to invoke the function. It not hard:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e1d660fff0bb0557c6042c89a63eef/href">https://medium.com/media/c3e1d660fff0bb0557c6042c89a63eef/href</a></iframe><p>And that&#39;s it, we did our solution in a pure and abstract way. Our code doesn&#39;t depend of an specific Monad, you can use any that you would like to. That means that you can change from technologies (like between Coroutines and RxJava) easily.</p><p>The code is easier to maintain because you can add new technologies/classes as long as they keep being Monads. It is also easier to reason about because you can cause all side effects at one single place.</p><p>I am pasting all the code here so you can take a look at the big picture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c48f3ea5458a20eebabe6c7d25250b40/href">https://medium.com/media/c48f3ea5458a20eebabe6c7d25250b40/href</a></iframe><p>This final version of the code may look a lot generic at first (the idea of using Kind&lt;F, T&gt; totally blowed my mind at first hahaha), but if you give it a try, you can definitely understand the idea and implement using this pattern without problems.</p><p>I hope you enjoyed the article and you start using Arrow and Category Theory. Happy coding!</p><p>If you enjoyed this article, please click on the clap button =]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8f22cdf54c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrow 101 - Building an Android app using Functional Programming]]></title>
            <link>https://medium.com/@lehen01/arrow-101-building-an-android-app-using-functional-programming-fe959675d96d?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe959675d96d</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Mon, 18 Jun 2018 01:41:51 GMT</pubDate>
            <atom:updated>2018-07-16T19:23:54.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Arrow 101 — Building an Android app using Functional Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HJJpOQE8M1-xXW0_5eePQ.png" /></figure><h3>1 — Intro</h3><p>Functional programming might seam a little bit challenging at first, but once you give it a try, you&#39;ll see that it comes with great benefits. The immutability makes the code a lot easier to reason about, to test and maintain. You don&#39;t need so many patterns and so many libraries in order make good quality code. Just by using the principles of functional programming you can make your code shine.</p><p>Although Kotlin is not a functional programming language, any developer can use <a href="https://arrow-kt.io/">Arrow</a> and gain many nice features for functional programming. Arrow adds new types like Option, Try, Either, IO, Functor, Applicative, Monad, High order abstractions, Type Classes and many more. In this article I am not going to explain the theory behind Arrow and functional programming, but instead show how to build a simple app using only functions so you can have a direction on your first steps into functional programming for Android.</p><h3>1.1 — About the project</h3><p>The project uses MVP. It reads from the Github API, so we don&#39;t have to worry about creating an API to interact with our app and focus on what matters. Our control and model layer are composed only by functions, but it is still necessary to keep the activity code as OOP, as you will see.</p><p>Don&#39;t worry if the concepts and code seam a bit odd at first, It took me a while to get it too! But, once it starts to make sense, you will see that FP (Functional Programming) is actually a lot simpler.</p><p>You can check the code in this repository: <a href="https://github.com/leandroBorgesFerreira/ArrowTry">https://github.com/leandroBorgesFerreira/ArrowTry</a></p><p>So, let&#39;s start?</p><h3>2 — The View (Activity)</h3><p>The code in our activity is not different from what you&#39;re probably used to:</p><pre><strong>class </strong>MainActivity : AppCompatActivity(), RepositoriesView {<br><br>    <strong>private val repoList </strong>: MutableList&lt;Repository&gt; = <em>mutableListOf</em>()<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_main</em>)<br><br>        setupList(<strong>repoList</strong>)<br>    }<br><br>    <strong>private fun </strong>setupList(listItems : List&lt;Repository&gt;) {<br>        heroesListRV.layoutManager = LinearLayoutManager(<strong>this</strong>)<br>        heroesListRV.adapter = RepositoriesAdapter(listItems, <strong>{ </strong>Log.d(<strong>&quot;Click&quot;</strong>, <strong>&quot;Got a click!&quot;</strong>) <strong>}</strong>)<br>    }<br><br>    <strong>override fun </strong>onResume() {<br>        <strong>super</strong>.onResume()<br>        <em>getRepositories</em>().<strong>run</strong>(RepositoriesDeps(<strong>this</strong>))<br>    }<br><br>    <strong>override fun </strong>showGenericError() {<br>        runOnUiThread <strong>{<br>            </strong>alert(<strong>&quot;Generic error!!&quot;</strong>) <strong>{<br>                </strong>yesButton <strong>{ }<br>            }</strong>.show()<br>        <strong>}<br>    </strong>}<br><br>    <strong>override fun </strong>drawRepositories(heroes: List&lt;Repository&gt;) {<br>        runOnUiThread <strong>{<br>            repoList</strong>.addAll(heroes)<br>            repositoryListRV.<em>adapter</em>.notifyDataSetChanged()<br>        <strong>}<br>    </strong>}<br>}</pre><pre><strong>data class </strong>RepositoriesDeps(<strong>val view</strong>: RepositoriesView)</pre><blockquote>Note: I am using <a href="https://github.com/Kotlin/anko">Anko</a> to create the Alert Dialog.</blockquote><p>This activity gets Repositories from Github API, updates an Adapter to exhibit the repositories then and provides a click listener.</p><p>The interesting part is this one:</p><pre><em>getRepositories</em>().<strong>run</strong>(RepositoriesDeps(<strong>this</strong>))</pre><p>This is a method from our presenter. This is a Reader monad that we are using to inject the View that the presenter needs in order to control the view. You can check this concept here: <a href="https://medium.com/@JorgeCastilloPr/kotlin-dependency-injection-with-the-reader-monad-7d52f94a482e">https://medium.com/@JorgeCastilloPr/kotlin-dependency-injection-with-the-reader-monad-7d52f94a482e</a>.</p><p>Don&#39;t worry about being an expert in Monads, just remember that this is a function that holds dependencies that our functions needs. If we don&#39;t pass the view to the presenter it wouldn&#39;t be MVP. All our dependencies can reside inside RepositoriesDeps. Although we only use <strong>View, </strong>we could have also added<strong> </strong>a<strong> Navigator </strong>or an <strong>API client.</strong></p><p>Before we finish this section, you might be thinking &quot;But why not have functions in the View?&quot;. Since we need the Context/Views to be able to draw our screen, the presenter wouldn&#39;t be able to call the functions directly, so we can&#39;t use functions in the View with MVP.</p><p>Now, next section.</p><h3>2 — The Presenter</h3><p>So, let&#39;s build the skeleton of <em>getRepositories</em>().</p><pre><strong>fun </strong>getRepositories() : Reader&lt;RepositoriesDeps, Unit&gt; =<br>        ReaderApi.ask&lt;RepositoriesDeps&gt;()</pre><p>Right now we have a function that receives some dependencies and does nothing. So, how can we add some behaviour to it?</p><p><strong>Reader</strong> has the following method:</p><pre><strong>fun </strong>&lt;D, A, B&gt; Reader&lt;D, A&gt;.map(f: (A) -&gt; B): Reader&lt;D, B&gt; = map(IdBimonad, f)</pre><p>Let&#39;s take a look. We need a function that takes A (Unit) and then makes it something else. <strong>f: (A) -&gt; B</strong>. By providing this function, we can add behaviour. Like this:</p><pre><strong>fun </strong>getRepositories() : Reader&lt;RepositoriesDeps, Unit&gt; =<br>        ReaderApi.ask&lt;RepositoriesDeps&gt;()<br>            .<em>map </em><strong>{ </strong>(view) <strong>-&gt;<br>                 </strong><em>repositoryUseCase</em>()<br>                   .unsafeRunAsync <strong>{ </strong>reposEither <strong>-&gt;<br>                     </strong>reposEither.fold(<br>                         <strong>{ </strong>view.showGenericError() <strong>}</strong>,<br>                         <strong>{ </strong>reposList <strong>-&gt; </strong><em>drawRepos</em>(reposList, view)<strong>}</strong>)<br>                   <strong>}<br>            }</strong></pre><p><em>repositoryUseCase()</em> is from our Model Layer, our Use Case. It will return an IO, but more on that latter. <strong>unsafeRunAsync </strong>takes<strong> </strong>as a parameter an <strong>Either</strong>. <strong>Either</strong> is a Data Type that can have two states, in our case it could be the list of Repositories or an Exception, in case some problem occurred. You can check more about the Either in this part of Arrow&#39;s documentation: <a href="https://arrow-kt.io/docs/datatypes/either/">https://arrow-kt.io/docs/datatypes/either/</a></p><pre><strong>private fun </strong>drawRepos(repositoryList: List&lt;Repository&gt;, view: RepositoriesView) {<br>    repositoryList.<br>            <em>sortedByDescending </em><strong>{ <br>                </strong>repository <strong>-&gt; </strong>repository.<strong>stargazersCount <br>            } </strong><em>pipe </em><strong>{ </strong>view.drawHeroes(<strong>it</strong>) <strong>}<br></strong>}</pre><p>Than we just draw the information. You can use <strong><em>pipe</em></strong> to create nice compositions of functions, it basically takes the result of the previous function and passes to the next one. It can make a code easier to read when creating big compositions of functions.</p><h3>3 — The Model Layer</h3><p>Then, we have our use case:</p><pre><strong>fun </strong>repositoryUseCase(): IO&lt;List&lt;Repository&gt;&gt; = <em>fetchAllRepositories</em>()</pre><p>And that&#39;s it. We could add some logic for cache… but I don&#39;t see why complicate this example.</p><p>And our data source:</p><pre><strong>private fun </strong>queryForRepositories(): Try&lt;List&lt;Repository&gt;&gt; =<br>        Try <strong>{<br>            </strong><em>apiClient</em>()<br>                    .getRepositories(<strong>&quot;Java&quot;</strong>, <strong>&quot;star&quot;</strong>, 1)<br>                    .execute()<br>                    .body()!!<br>                    .<strong>items<br>        }</strong></pre><pre><strong>fun </strong>fetchAllRepositories(): IO&lt;List&lt;Repository&gt;&gt; =<br>        IO.async <strong>{ </strong>either <strong>-&gt;<br>            </strong><em>async </em><strong>{<br>                </strong>either(<em>queryForRepositories</em>().toEither())<br>            <strong>}<br>        }</strong></pre><p><em>You may be thinking: &quot;If I don&#39;t receive the apiClient as a parameter, how am I going to test this?&quot; In the next section, I&#39;ll show how to inject the apiClient, but let&#39;s keep it simple for now.</em></p><p>The first function makes a synchronous call to the API (I am using Retrofit, but that&#39;s not really important here) and the result is wrapped in a <strong>Try</strong>. <strong>Try</strong> is also a Data type and it represents a computation that can return a value, if the computation is successful, or return an error if it goes wrong. It substitutes the try/catch in a more functional approach because we always get a result from out computation. Simply catching an Exception in another block of code would be odd because a function should always return a result, right?</p><p>The second function returns an IO. First we use the IO.async. It is a function made for integrations with asynchronous calls. It runs until the callback parameter is invoked. It uses Coroutines so we don&#39;t make a network call in the main thread.</p><p>So now we have everything we need. All you have to do is to implement the apiClient() part of you app, but I will leave that to you as this is no different from what you are used(or you can just check the code in the repository). In my app I got this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*7TodC2uxBIMHqsVj6CB4PQ.png" /></figure><p>With very little code and few new concepts we could create a small app without the need of classes to control its logic. This way we can avoid state in our code and the use of complex libraries, all we have to do it to trust in the concepts of FP.</p><h3><strong>4 — Improving the code (for tests)</strong></h3><p>This code is not testable, because we can&#39;t mock the apiClient. So how to handle this? Well, the same way we did in the Presenter. We are going to use a Reader.</p><p>First we add the apiClient in the RepositoriesDeps:</p><pre><strong>data class </strong>RepositoriesDeps(<strong>val view</strong>: RepositoriesView, <br>                            <strong>val apiClient</strong>: ApiClient)</pre><p>And, in our activity, we write:</p><pre><strong>override fun </strong>onResume() {<br>    <strong>super</strong>.onResume()<br>    <em>getRepositories</em>().<strong>run</strong>(RepositoriesDeps(<strong>this</strong>, <em>apiClient</em>()))<br>}</pre><p>The DataSource:</p><pre><strong>fun </strong>fetchAllRepositories(): Reader&lt;RepositoriesDeps, IO&lt;List&lt;Repository&gt;&gt;&gt; =<br>        ReaderApi.ask&lt;RepositoriesDeps&gt;()<br>                .<em>map </em><strong>{ </strong>deps <strong>-&gt;<br>                         </strong>IO.async&lt;List&lt;Repository&gt;&gt; <strong>{ </strong>either <strong>-&gt;<br>                             </strong><em>async </em><strong>{<br>                                 </strong>either(<em>queryForRepositories</em>(deps.<strong>apiClient</strong>).toEither())<br>                             <strong>}<br>                         }<br>                     }</strong></pre><pre><strong>private fun </strong>queryForRepositories(apiClient: ApiClient): Try&lt;List&lt;Repository&gt;&gt; =<br>        Try <strong>{<br>            </strong>apiClient<br>                    .getRepositories(<strong>&quot;Java&quot;</strong>, <strong>&quot;star&quot;</strong>, 1)<br>                    .execute()<br>                    .body()!!<br>                    .<strong>items<br>        }</strong></pre><p>We did the same as in the Presenter. We use a Reader that asks for the dependencies that we need. Now the can inject our ApiClient as a dependency in the <em>queryForRepositories()</em> function.</p><p>Use case:</p><pre><strong>fun </strong>repositoryUseCase() : Reader&lt;RepositoriesDeps, IO&lt;List&lt;Repository&gt;&gt;&gt; = <em>fetchAllRepositories</em>()</pre><p>As the last part, we need to change the Presenter:</p><pre><strong>fun </strong>getRepositories(): Reader&lt;RepositoriesDeps, Unit&gt; =<br>        ReaderApi.ask&lt;RepositoriesDeps&gt;()<br>            .<em>flatMap </em><strong>{ </strong>(view, _) <strong>-&gt;<br>                 </strong><em>repositoryUseCase</em>()<br>                     .<em>map </em><strong>{ </strong>io <strong>-&gt;<br>                              </strong>io.unsafeRunAsync <strong>{ </strong>reposEither <strong>-&gt;<br>                                  </strong>reposEither.fold(<br>                                          <strong>{ </strong>view.showGenericError() <strong>}</strong>,<br>                                          <strong>{ </strong>reposList <strong>-&gt; </strong><em>drawRepos</em>(reposList, view) <strong>}</strong>)<br>                              <strong>}<br>                          } </strong><br><br>             <strong>} </strong></pre><p>Ok, now the code can the confusing. First, we cannot use <em>map</em> anymore, because our <em>repositoryUseCase()</em> does not return an IO, it returns a Reader. We are not respecting the signature:<em> f: (A) -&gt; B </em>. We are instead using: <em>(A) -&gt; Reader&lt;D, B&gt;</em>. But there is no problem, we can use flatMap that handles this problem. Take a look at the signature:</p><pre>Reader&lt;D, A&gt;.flatMap(f: (A) -&gt; Reader&lt;D, B&gt;): Reader&lt;D, B&gt;</pre><p>Using <em>flatMap() </em>we can change the content type (A) of our <strong>Reader </strong>and add behaviour using the function<strong> f</strong>.</p><p>We then map the answer of our <em>repositoryUseCase </em>function and we have the same behaviour as before.</p><p>Now we have a clean and easy to test code. The same approach can be used in more complex scenarios with no problem.</p><h3><strong>5 — Final considerations</strong></h3><p>I hope you enjoyed to use FP in the Android world. It can be a bit hard if you&#39;re coming from Java, but after you get the concept, it goes just fine.</p><p>If you are interested in learning more about FP. I suggest this articles that explains about Functors, Applicatives and Monads in Kotlin: <a href="https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251">https://hackernoon.com/kotlin-functors-applicatives-and-monads-in-pictures-part-1-3-c47a1b1ce251</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe959675d96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a custom view with Data binding: It's so simple!]]></title>
            <link>https://medium.com/android-news/creating-a-custom-view-with-data-binding-its-so-simple-520923d775cd?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/520923d775cd</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Thu, 24 Aug 2017 19:16:11 GMT</pubDate>
            <atom:updated>2017-08-24T19:16:11.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yknR1adD0owUrN7iZRSVw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/yjTxnh7bsdw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Foto Garage AG</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>1 — Intro</h3><p>Sometimes we use the same UI element many times in our project. A smart way to avoid repeating the same code over and over is to create a CustomView or a fragment to encapsulate the desired behavior.</p><p>But, sometimes, creating custom views or managing fragments lifecycle may be over complicated. You usually end up with a custom view with a lot of boiler plate code or nested fragments with complex life cycles. A really simple way to deal with this problem is to use data binding to create little pieces of reusable UI. We only need to write code in the XML and the communication with the component is made by the bindings.</p><p><em>The code for this article can be found in this repository: </em><a href="https://github.com/leandroBorgesFerreira/DataBindingComponentSample">https://github.com/leandroBorgesFerreira/DataBindingComponentSample</a></p><h3>2 — The project</h3><p>We are going to build a simple number keyboard to illustrate the use of data binding for creating UI components. This one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*u_RPVhrSW-KA5rR1JDCGiQ.gif" /><figcaption>recoded with Giphy and Vysor</figcaption></figure><p>Nothing really special here. The interesting part is HOW we do it.</p><h3>3 — Let&#39;s create XML of the keyboard</h3><p>You can construct the keyboard with the code in the next gist. It has a lot of lines, but it&#39;s just the some information over and over. I will explain the important part after the gist, so don&#39;t waste too much time on this piece code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/959abe97f75b814400e8b9265ae50d75/href">https://medium.com/media/959abe97f75b814400e8b9265ae50d75/href</a></iframe><p>The name of this xml is number_keyboard, this will be important later.</p><h3>4 — We need to communicate with the XML</h3><p>The communication parts (the important parts in the XML) are this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39b00c4e92baa70529408c026ba11f52/href">https://medium.com/media/39b00c4e92baa70529408c026ba11f52/href</a></iframe><p>And this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/977daa84cb9652ca86c9c9999f077e86/href">https://medium.com/media/977daa84cb9652ca86c9c9999f077e86/href</a></iframe><p>We are importing the Actions so we can use some constants that we are going to define. We also need a listener for the button clicks. This is our keyListener, it is a variable in our XML and we are going to instantiate this when we finally use our library.</p><p>So we have a listener that will listen for the clicks in all the buttons. All we have to do now is to define the interface for this listener and our library is complete. No need for concrete classes!</p><p>So we define our listener:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5049d0ae7e9de91250545a66b50d5bf8/href">https://medium.com/media/5049d0ae7e9de91250545a66b50d5bf8/href</a></iframe><p>To make this library able to erase the text, we need to define a Char that ask for erase instead of writing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eacf57d76adf438d61da6dc63d3e3623/href">https://medium.com/media/eacf57d76adf438d61da6dc63d3e3623/href</a></iframe><p>So this is our library. Pretty easy, right?</p><p>So now all we need to use this library in a project. Let&#39;s do that.</p><h3>5 — Let&#39;s use our library</h3><p>So it is time to use the library. We didn&#39;t instantiate our keyListener, do you remember that? So we need to add the key listener in the XML of our activity. It will inside our viewModel, the class that coordinates our activity.</p><p>Our keyboard is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fff8b0d9d734cb08bde0b1da3a1a5f4/href">https://medium.com/media/2fff8b0d9d734cb08bde0b1da3a1a5f4/href</a></iframe><p>We use our library as a simple include. That&#39;s the magic: we don&#39;t need a fragment with a complex life cycle or a complicated custom view, all we have is a simple include.</p><p>For the communication we use a listener in our ViewModel. The ViewModel will be defined in our XML. Let&#39;s take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1533676621df390a60a3099222da4b73/href">https://medium.com/media/1533676621df390a60a3099222da4b73/href</a></iframe><p>We are defining our ViewModel. It has a testObservable that will receive the text inserted in the EditText. Please note that I am using two way data binding. The ViewModel also it has our listener.</p><p>So let&#39;s create our ViewModel</p><h3>6 — The ViewModel</h3><p>To coordinate our XML, we just need a simple ViewModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8984e38b5a926ed5820e8aa02abbe38/href">https://medium.com/media/d8984e38b5a926ed5820e8aa02abbe38/href</a></iframe><p>The onKeyClick is implementing the <strong>OnKeyClick</strong> interface that we defined in our library, that&#39;s how our communication works. The method <strong>receiveText()</strong> receives the character provided by Keyboard then evaluates if the command is to erase or to write and performs the right action.</p><h3>7 — Finally, the bind</h3><p>Create the activity and create the bind, simple as that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cc71bbfd9b8db66712818ef8f7dfdac/href">https://medium.com/media/8cc71bbfd9b8db66712818ef8f7dfdac/href</a></iframe><p>And that&#39;s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*rO34jp-bYSkCnHSdwoO3qQ.gif" /><figcaption>From giphy.com</figcaption></figure><h3>8 — Is this approach really better?</h3><p>My first try was to create a fragment to solve the keyboard problem. It seamed like a good solution and, at first, it worked just fine. But then I had to use the keyboard inside an another fragment in a ViewPager. This created some annoying problems with the life cycle of nested fragments for a very simple screen… nested fragments are just a nightmare o.O</p><p>So I decided to make a component using data binding. It made the project a lot simpler and my favorite part: <strong>No concrete classes</strong>! Just a simple interface for a listener. I used the same approach for some other views, and it worked fine. This is a scope of problem where data binding really shines!</p><p>But please remember that this is no silver bullet. If the problem you are trying to solve involves complex animations, the lack of Java/Kotlin code can make it impossible. Evaluate your needs before deciding to make a component with a fragment, custom view or data binding.</p><p><em>If you enjoyed reading this, please click the heart icon below. This will help to share the story with others. If you would like to see more content like this one, follow me.</em></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=520923d775cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/creating-a-custom-view-with-data-binding-its-so-simple-520923d775cd">Creating a custom view with Data binding: It&#39;s so simple!</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[Make a great Android UX: How to make a swipe button]]></title>
            <link>https://medium.com/android-news/make-a-great-android-ux-how-to-make-a-swipe-button-eefbf060326d?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/eefbf060326d</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Thu, 08 Jun 2017 05:59:20 GMT</pubDate>
            <atom:updated>2017-06-08T05:59:20.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*isRdvxB7y0pkZE8Wcwa6ug.gif" /></figure><p>Design not about making something beautiful, it is about making something great. You can do a great app by many ways, but one of my favorites is to make it the simplest and intuitive as possible, yet being original. It is important for your UI to respond to the user accordingly to importance of a certain action. Sometimes this action is too much important to be triggered by a simple click, like unlock your smartphone for example. Click in a button and receive a confirm dialog is ok. It works. But everybody does that! What can&#39;t we make something different!?</p><p>Well, today we will.</p><p>In this tutorial I am going to show how to make a swipe button. It allows the user to make an important action without necessarily having to confirm his/her intentions, because it is hard to swipe the button by accident (But please remember: It is not impossible. So take care!). So you have a much more intuitive, nicer and simpler UX.</p><p>Cool right? So let&#39;s go!</p><p><em>This tutorial is based in this repository: </em><a href="https://github.com/ebanx/swipe-button/"><em>https://github.com/ebanx/swipe-button/ </em></a><em>. If you prefer to just use the button, you can simply add it in your app using Gradle.</em></p><h3>Part 1 — Let&#39;s define our xml</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*QnKpO9oqDOhx_ne149m93w.gif" /><figcaption>from giphy</figcaption></figure><p>Our button has a circle moving part and a rounded background. So let&#39;s make those parts:</p><p>The circle, <strong>shape_button.xml</strong></p><pre>&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>&lt;item&gt;<br>    &lt;shape android:shape=&quot;rectangle&quot;&gt;<br>        &lt;corners android:radius=&quot;50dp&quot; /&gt;<br>        &lt;solid android:color=&quot;@android:color/white&quot; /&gt;<br>    &lt;/shape&gt;<br>&lt;/item&gt;<br>&lt;/selector&gt;</pre><p>And the background, <strong>shape_rounded.xml</strong></p><pre>&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>&lt;item android:state_pressed=&quot;false&quot; android:state_selected=&quot;false&quot;&gt;<br>    &lt;shape android:shape=&quot;rectangle&quot;&gt;<br>        &lt;corners android:radius=&quot;150dp&quot; /&gt;<br>        &lt;solid android:color=&quot;#4D6070&quot; /&gt;<br>    &lt;/shape&gt;<br>&lt;/item&gt;<br>&lt;/selector&gt;</pre><p>The radius can be any number that is very, so the borders are a semi-circle. You can use different colors if your prefer.</p><p>So now we have the xml that we next. Let&#39;s start making our custom view.</p><h3>Part 2 — Starting to make a custom view</h3><p>We are going to extend RelativeLayout, like this:</p><pre>public class SwipeButton extends RelativeLayout {<br>    <strong>private </strong>ImageView <strong>slidingButton</strong>;<br>    <strong>private float initialX</strong>;<br>    <strong>private boolean active</strong>;<br>    <strong>private int initialButtonWidth</strong>;<br>    <strong>private </strong>TextView <strong>centerText</strong>;<br><br>    <strong>private </strong>Drawable <strong>disabledDrawable</strong>;<br>    <strong>private </strong>Drawable <strong>enabledDrawable</strong>;</pre><pre>    public SwipeButton(Context context) {<br>        super(context);<br><br>        init(context, null, -1, -1);<br>    }<br><br>    public SwipeButton(Context context, AttributeSet attrs) {<br>        super(context, attrs);<br><br>        init(context, attrs, -1, -1);<br>    }<br><br>    public SwipeButton(Context context, AttributeSet attrs, int defStyleAttr) {<br>        super(context, attrs, defStyleAttr);<br><br>        init(context, attrs, defStyleAttr, -1);<br>    }<br><br>    @TargetApi(21)<br>    public SwipeButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {<br>        super(context, attrs, defStyleAttr, defStyleRes);<br>        init(context, attrs, defStyleAttr, defStyleRes);<br>    }</pre><pre>    private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {<br>    //Don&#39;t worry about this method right now... I&#39;m going to talk about this latter. </pre><pre>}</pre><p>So you must me thinking… &quot;This is a button, why are we extending a RelativeLayout??&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*TBZsWCDlldF-hU7R8XOzOg.gif" /><figcaption>Calm down! We are going to figure this out!</figcaption></figure><p>As this is a complex button, we need to to add many views to be able to accomplish the behavior we need, so we need a ViewGroup. RelativeLayout is a good option because many views will overlap in this component.</p><p>We have many inner views. So let&#39;s split this implementation in steps.</p><p>It also important for you the understand the variables of this class:</p><p><strong>slidingButton</strong> -&gt; This is the moving part of the component. It contains the icon.</p><p><strong>initialX</strong> -&gt; It is the position of the moving part when the user is going to start to move it.</p><p><strong>active</strong> -&gt; It is the variable that says that the button is active or not.</p><p><strong>initialButtonWidth</strong> -&gt; This the initial width of the moving part. We need to save it so we can morph back to the initial position.</p><p><strong>centerText</strong> -&gt;The text in the center of the button.</p><p><strong>disabledDrawable</strong> / <strong>enabledDrawable</strong> -&gt; The icons that the moving part is going to hold when the button is enabled or disabled. Use the icon that you prefer.</p><h4>The background</h4><p>First, we add a background</p><pre><strong>private void </strong>init(Context context, AttributeSet attrs, <strong>int </strong>defStyleAttr, <strong>int </strong>defStyleRes) {<br>    RelativeLayout background = <strong>new </strong>RelativeLayout(context);<br><br>    LayoutParams layoutParamsView = <strong>new </strong>LayoutParams(<br>        ViewGroup.LayoutParams.<strong><em>MATCH_PARENT</em></strong>,<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>);<br><br>    layoutParamsView.addRule(RelativeLayout.<strong><em>CENTER_IN_PARENT</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);<br><br>    background.setBackground(ContextCompat.<em>getDrawable</em>(context, R.drawable.<strong><em>shape_rounded</em></strong>));<br><br>    addView(background, layoutParamsView);</pre><p>This is the view responsible to the rounded background of the button.</p><h4>The text</h4><p>Now we have to add a informative text in the button</p><pre><strong>inal </strong>TextView centerText = <strong>new </strong>TextView(context);<br><strong>this</strong>.<strong>centerText </strong>= centerText;<br><br>LayoutParams layoutParams = <strong>new </strong>LayoutParams(<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>,<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>);<br><br>layoutParams.addRule(RelativeLayout.<strong><em>CENTER_IN_PARENT</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);<br>centerText.setText(<strong>&quot;SWIPE&quot;</strong>); <em>//add any text you need<br></em>centerText.setTextColor(Color.<strong><em>WHITE</em></strong>);<br>centerText.setPadding(35, 35, 35, 35);<br>background.addView(centerText, layoutParams);</pre><p>This is the text in the center of the component. I am hard coding the text for simplicity, but you can use string resources for internationalization. You can add the padding that you prefer. That is the way you control the size of your component background.</p><h4>Add the moving icon</h4><pre><strong>final </strong>ImageView swipeButton = <strong>new </strong>ImageView(context);<br><strong>this</strong>.<strong>slidingButton </strong>= swipeButton;<br><br><strong>disabledDrawable </strong>= ContextCompat.<em>getDrawable</em>(getContext(), R.drawable.<strong><em>ic_lock_open_black_24dp</em></strong>);<br><strong>enabledDrawable </strong>= ContextCompat.<em>getDrawable</em>(getContext(), R.drawable.<strong><em>ic_lock_outline_black_24dp</em></strong>);<br><br><strong>slidingButton</strong>.setImageDrawable(<strong>disabledDrawable</strong>);<br><strong>slidingButton</strong>.setPadding(40, 40, 40, 40);<br><br>LayoutParams layoutParamsButton = <strong>new </strong>LayoutParams(<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>,<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>);<br><br>layoutParamsButton.addRule(RelativeLayout.<strong><em>ALIGN_PARENT_LEFT</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);<br>layoutParamsButton.addRule(RelativeLayout.<strong><em>CENTER_VERTICAL</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);<br>swipeButton.setBackground(ContextCompat.<em>getDrawable</em>(context, R.drawable.<strong><em>shape_button</em></strong>));<br>swipeButton.setImageDrawable(<strong>disabledDrawable</strong>);<br>addView(swipeButton, layoutParamsButton);</pre><p>This is the moving part of the component. We have to set the icons for the disabled and enabled states. Setting the padding is the way to set the size of the moving part of the component.</p><h4>Add a touch listner</h4><pre>setOnTouchListener(getButtonTouchListener());</pre><p>Add this line add the end of init method. We are going to see more about this in the next section. Then, the init is going to be:</p><pre><strong>private void </strong>init(Context context, AttributeSet attrs, <strong>int </strong>defStyleAttr, <strong>int </strong>defStyleRes) {<br>    RelativeLayout background = <strong>this</strong>;<br><br>    LayoutParams layoutParamsView = <strong>new </strong>LayoutParams(<br>        ViewGroup.LayoutParams.<strong><em>MATCH_PARENT</em></strong>,<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>);<br><br>    layoutParamsView.addRule(RelativeLayout.<strong><em>CENTER_IN_PARENT</em></strong>,   RelativeLayout.<strong><em>TRUE</em></strong>);<br><br>    background.setBackground(ContextCompat.<em>getDrawable</em>(context, R.drawable.<em>shape_rounded</em>));</pre><pre>    addView(background, layoutParamsView);</pre><pre><strong>    final </strong>TextView centerText = <strong>new </strong>TextView(context);<br>    <strong>this</strong>.<strong>centerText </strong>= centerText;<br>    centerText.setGravity(Gravity.<strong><em>CENTER</em></strong>);<br><br>    LayoutParams layoutParams = <strong>new </strong>LayoutParams(<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>,<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>);<br><br>    layoutParams.addRule(RelativeLayout.<strong><em>CENTER_IN_PARENT</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);</pre><pre>    centerText.setText(&quot;SWIPE&quot;); //add any text you need<br>    centerText.setTextColor(Color.<strong><em>WHITE</em></strong>);</pre><pre>    background.addView(centerText, layoutParams);</pre><pre><strong>    final </strong>ImageView swipeButton = <strong>new </strong>ImageView(context);<br>    <strong>this</strong>.<strong>slidingButton </strong>= swipeButton;<br><br>    LayoutParams layoutParamsButton = <strong>new </strong>LayoutParams(<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>,<br>        ViewGroup.LayoutParams.<strong><em>WRAP_CONTENT</em></strong>);<br><br>    layoutParamsButton.addRule(RelativeLayout.<strong><em>ALIGN_PARENT_LEFT</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);<br>    layoutParamsButton.addRule(RelativeLayout.<strong><em>CENTER_VERTICAL</em></strong>, RelativeLayout.<strong><em>TRUE</em></strong>);</pre><pre>    swipeButton.setBackground(ContextCompat.<em>getDrawable</em>(context, R.drawable.<em>shape_button</em>));</pre><pre>    swipeButton.setImageDrawable(<strong>disabledDrawable</strong>);</pre><pre>    addView(swipeButton, layoutParamsButton);</pre><pre>    setOnTouchListener(getButtonTouchListener());<br>}</pre><p>So right now you can add this button in your app and see the result. Like this:</p><pre>&lt;your.package.here<strong>.SwipeButton<br>    android:id=&quot;@+id/swipe_btn&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;100dp&quot;<br>    android:layout_marginStart=&quot;20dp&quot;<br>    android:layout_marginEnd=&quot;20dp&quot;<br>    </strong>/&gt;</pre><p>The button will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Ash4UbIPVuWe1lxJ1svXKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*abmjqWHX3sniIz6sgT-2tw.gif" /><figcaption>Nice!</figcaption></figure><p>Ok this is looking good so far. But we not behavior yet. In the next section, you will some logic to your component!</p><h3>Part 3 — Implementing the button login</h3><p>Let&#39;s implment the getButtonTouchListener.</p><pre><strong>private </strong>OnTouchListener getButtonTouchListener() {<br>    <strong>return new </strong>OnTouchListener() {<br>        @Override<br>        <strong>public boolean </strong>onTouch(View v, MotionEvent event) {<br>        <strong>switch </strong>(event.getAction()) {<br>            <strong>case </strong>MotionEvent.<strong><em>ACTION_DOWN</em></strong>:<br>                <strong>return true</strong>;<br>            <strong>case </strong>MotionEvent.<strong><em>ACTION_MOVE</em></strong>: <br>                //Movement logic here<br>                <strong>return true</strong>;<br>            <strong>case </strong>MotionEvent.<strong><em>ACTION_UP</em></strong>:              </pre><pre>                //Release logic here<br>                <strong>return true</strong>;<br>            }<br><br>        <strong>return false</strong>;<br>        }<br>    };<br>}</pre><p>Now we have our listener. Let&#39;s add the logic inside the ACTION_MOVE case.</p><h4>Movement logic</h4><pre><strong>if </strong>(<strong>initialX </strong>== 0) {<br>    <strong>initialX </strong>= <strong>slidingButton</strong>.getX();<br>}</pre><pre><strong>if </strong>(event.getX() &gt; <strong>initialX </strong>+ <strong>slidingButton</strong>.getWidth() / 2 &amp;&amp;<br>        event.getX() + <strong>slidingButton</strong>.getWidth() / 2 &lt; getWidth()) {<br>    <strong>slidingButton</strong>.setX(event.getX() - <strong>slidingButton</strong>.getWidth() / 2);<br>    <strong>centerText</strong>.setAlpha(1 - 1.3f * (<strong>slidingButton</strong>.getX() + <strong>slidingButton</strong>.getWidth()) / getWidth());<br>}<br><br><strong>if  </strong>(event.getX() + <strong>slidingButton</strong>.getWidth() / 2 &gt; getWidth() &amp;&amp;<br>        <strong>slidingButton</strong>.getX() + <strong>slidingButton</strong>.getWidth() / 2 &lt; getWidth()) {<br>    <strong>slidingButton</strong>.setX(getWidth() - <strong>slidingButton</strong>.getWidth());<br>}<br><br><strong>if  </strong>(event.getX() &lt; <strong>slidingButton</strong>.getWidth() / 2 &amp;&amp;<br>        <strong>slidingButton</strong>.getX() &gt; 0) {<br>    <strong>slidingButton</strong>.setX(0);<br>}</pre><p>Let&#39;s explain those IFs.</p><p>The first one is just to make sure that we know the initial position of the button, in case it is not zero.</p><p>The second IF is the one responsible to make the button follow the finger of the user. <strong>event.getX()</strong> returns the positions of the current touch. In this part of the code, we set the center of the button in the position of the touch and we decrease the alpha of the text as the swipe increases.</p><p>The third and the fourth IFs are responsible to set the moving part position to the limits of the component when the user swipes outside of the limits.</p><h4>Release logic</h4><p>In the release, we need three methods:</p><pre><strong>case </strong>MotionEvent.<strong><em>ACTION_UP</em></strong>:<br>    <strong>if </strong>(<strong>active</strong>) {<br>        collapseButton();<br>    } <strong>else </strong>{<br>        <strong>initialButtonWidth </strong>= <strong>slidingButton</strong>.getWidth();<br><br>        <strong>if </strong>(<strong>slidingButton</strong>.getX() + <strong>slidingButton</strong>.getWidth() &gt; getWidth() * 0.85) {<br>            expandButton();<br>        } <strong>else </strong>{<br>            moveButtonBack();<br>        }<br>    }<br><br>    <strong>return true</strong>;<br>}</pre><p>If the button is released and it is active, we need it to collapse. If the button is released very close to the final of the swipe, then need it to expand. If the button is release far away from the right edge, it must animate the way back.</p><p>Those are the animations:</p><h4>expand animation</h4><pre><strong>private void </strong>expandButton() {<br>    <strong>final </strong>ValueAnimator positionAnimator =<br>            ValueAnimator.<em>ofFloat</em>(<strong>slidingButton</strong>.getX(), 0);<br>    positionAnimator.addUpdateListener(<strong>new </strong>ValueAnimator.AnimatorUpdateListener() {<br>        @Override<br>        <strong>public void </strong>onAnimationUpdate(ValueAnimator animation) {<br>            <strong>float </strong>x = (Float) positionAnimator.getAnimatedValue();<br>            <strong>slidingButton</strong>.setX(x);<br>        }<br>    });<br><br><br>    <strong>final </strong>ValueAnimator widthAnimator = ValueAnimator.<em>ofInt</em>(<br>            <strong>slidingButton</strong>.getWidth(),<br>            getWidth());<br><br>    widthAnimator.addUpdateListener(<strong>new </strong>ValueAnimator.AnimatorUpdateListener() {<br>        @Override<br>        <strong>public void </strong>onAnimationUpdate(ValueAnimator animation) {<br>            ViewGroup.LayoutParams params = <strong>slidingButton</strong>.getLayoutParams();<br>            params.<strong>width </strong>= (Integer) widthAnimator.getAnimatedValue();<br>            <strong>slidingButton</strong>.setLayoutParams(params);<br>        }<br>    });<br><br><br>    AnimatorSet animatorSet = <strong>new </strong>AnimatorSet();<br>    animatorSet.addListener(<strong>new </strong>AnimatorListenerAdapter() {<br>        @Override<br>        <strong>public void </strong>onAnimationEnd(Animator animation) {<br>            <strong>super</strong>.onAnimationEnd(animation);<br><br>            <strong>active </strong>= <strong>true</strong>;<br>            <strong>slidingButton</strong>.setImageDrawable(<strong>enabledDrawable</strong>);            <br>        }<br>    });<br><br>    animatorSet.playTogether(positionAnimator, widthAnimator);<br>    animatorSet.start();<br>}</pre><p>This animation is a bit complicated right? Don&#39;t worry, you got this! Let me explain:</p><p>First, the slidingButton is going to animate do the left edge of our component. That&#39;s the <strong>positionAnimator</strong>.</p><p>Second, the button must expand and occupy the entire space of the component. That the <strong>widthAnimator</strong>.</p><p>Third, we create an AnimatorSet so we can play the animations together. At the end of the animation, we set the state of the button as active and change the image of the button.</p><h4>Collapse animation</h4><pre><strong>private void </strong>collapseButton() {<br>    <strong>final </strong>ValueAnimator widthAnimator = ValueAnimator.<em>ofInt</em>(<br>            <strong>slidingButton</strong>.getWidth(),<br>            <strong>initialButtonWidth</strong>);<br><br>    widthAnimator.addUpdateListener(<strong>new </strong>ValueAnimator.AnimatorUpdateListener() {<br>        @Override<br>        <strong>public void </strong>onAnimationUpdate(ValueAnimator animation) {<br>            ViewGroup.LayoutParams params =  <strong>slidingButton</strong>.getLayoutParams();<br>            params.<strong>width </strong>= (Integer) widthAnimator.getAnimatedValue();<br>            <strong>slidingButton</strong>.setLayoutParams(params);<br>        }<br>    });<br><br>    widthAnimator.addListener(<strong>new </strong>AnimatorListenerAdapter() {<br>        @Override<br>        <strong>public void </strong>onAnimationEnd(Animator animation) {<br>            <strong>super</strong>.onAnimationEnd(animation);<br>            <strong>active </strong>= <strong>false</strong>;<br>            <strong>slidingButton</strong>.setImageDrawable(<strong>disabledDrawable</strong>);<br>        }<br>    });<br><br>    ObjectAnimator objectAnimator = ObjectAnimator.<em>ofFloat</em>(<br>            <strong>centerText</strong>, <strong>&quot;alpha&quot;</strong>, 1);<br><br>    AnimatorSet animatorSet = <strong>new </strong>AnimatorSet();<br><br>    animatorSet.playTogether(objectAnimator, widthAnimator);<br>    animatorSet.start();<br>}</pre><p>This animation is similar to the expand button, but this time we increase the alpha of the text so it can become visible again.</p><h4>Move the button back</h4><pre><strong>private void </strong>moveButtonBack() {<br>    <strong>final </strong>ValueAnimator positionAnimator =<br>            ValueAnimator.<em>ofFloat</em>(<strong>slidingButton</strong>.getX(), 0);<br>    positionAnimator.setInterpolator(<strong>new </strong>AccelerateDecelerateInterpolator());<br>    positionAnimator.addUpdateListener(<strong>new </strong>ValueAnimator.AnimatorUpdateListener() {<br>        @Override<br>        <strong>public void </strong>onAnimationUpdate(ValueAnimator animation) {<br>            <strong>float </strong>x = (Float) positionAnimator.getAnimatedValue();<br>            <strong>slidingButton</strong>.setX(x);<br>        }<br>    });<br><br>    ObjectAnimator objectAnimator = ObjectAnimator.<em>ofFloat</em>(<br>            <strong>centerText</strong>, <strong>&quot;alpha&quot;</strong>, 1);<br><br>    positionAnimator.setDuration(200);<br><br>    AnimatorSet animatorSet = <strong>new </strong>AnimatorSet();<br>    animatorSet.playTogether(objectAnimator, positionAnimator);<br>    animatorSet.start();<br>}</pre><p>This animation move the button back to the left edge and recovers the alpha of the component text.</p><h3>Part 4 — The result</h3><p>If you did everything right you will get this (use a dark backgound in your activity):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*U_No0Q91wpLDhfp5AldTpg.gif" /></figure><p>And that&#39;s it, you made it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*VaC2zfBCafr1mmyuXH81kw.gif" /><figcaption>Congrats!</figcaption></figure><p><em>If you enjoyed reading this, please click the heart icon below. This will help to share the story with others. If you would like to see more content like this one, follow me.</em></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=eefbf060326d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/make-a-great-android-ux-how-to-make-a-swipe-button-eefbf060326d">Make a great Android UX: How to make a swipe button</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[Make your app shine #3: How to reveal an activity with circular revelation]]></title>
            <link>https://medium.com/android-news/a-little-thing-that-matter-how-to-reveal-an-activity-with-circular-revelation-d94f9bfcae28?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d94f9bfcae28</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Mon, 22 May 2017 16:50:01 GMT</pubDate>
            <atom:updated>2017-05-22T18:48:06.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*ZBwSTSkzwUFApLXL9LMkyw.gif" /></figure><p><em>Edit: Please keep in mind that, using this code keeps the last activity in memory, so remember to finish it after the animation or to use this in simple transitions. (Like a splash screen)</em></p><p>Micro interactions are so cool! Android makes possible to create many nice animations with little effort, so it is a good place to create very interactive software (and have fun while you do so!). This time, I will show how to reveal an activity with the circular reveal animation. This can be a really nice way to start a new activity from a circular button (a floating action button, for example)</p><h3>Part 1 — The skeleton of the project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*Y5f8_5uuD2wRTkCnjmGV9w.gif" /><figcaption>from giphy.com</figcaption></figure><p>I want you to focus on the animation, so I am going to create two really simple activities with solid colors, a text and a button. You can get your hands dirty and make an amazing UI after you learn the animation!</p><p>XML for activity 1:</p><pre>&lt;<strong>RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:padding=&quot;16dp&quot;<br>    android:fitsSystemWindows=&quot;true&quot;<br>    android:background=&quot;@android:color/background_dark&quot;<br>    tools:context=&quot;com.ebanx.circularreveal.MainActivity&quot;</strong>&gt;<br><br>    &lt;<strong>TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;First activity&quot;<br>        android:layout_centerHorizontal=&quot;true&quot;<br>         </strong>/&gt;<br><br>    &lt;<strong>Button<br>        android:id=&quot;@+id/btn&quot;<br>        android:layout_width=&quot;70dp&quot;<br>        android:layout_height=&quot;70dp&quot;<br>        android:text=&quot;GO!&quot;<br>        android:textColor=&quot;@android:color/white&quot;<br>        android:layout_centerInParent=&quot;true&quot;<br>        android:background=&quot;@drawable/button_shape&quot;</strong>/&gt;<br><br>&lt;/<strong>RelativeLayout</strong>&gt;</pre><p>I made the activity with a black background because I want you to see very clearly the animation to the second activity.</p><p>I used custom background for the button to make it a circle. Please remind that this animation needs to be used in the right place. It wouldn’t look very nice with a squared button, for example (or maybe it does!).</p><p>This is the button_shape:</p><pre>&lt;<strong>shape android:shape=&quot;rectangle&quot;<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; </strong>&gt;<br><br>    &lt;<strong>corners android:radius=&quot;100dp&quot; </strong>/&gt;<br>    &lt;<strong>solid android:color=&quot;@color/colorPrimary&quot;</strong>/&gt;<br>&lt;/<strong>shape</strong>&gt;</pre><p>Code for activity 1:</p><pre><strong>public class </strong>MainActivity <strong>extends </strong>AppCompatActivity {<br><br>    <strong>private </strong>Button <strong>btnCreate</strong>;<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_main</em></strong>);<br><br>        <strong>btnCreate </strong>= (Button) findViewById(R.id.<strong><em>btn</em></strong>);<br><br>        <strong>btnCreate</strong>.setOnClickListener(<strong>new </strong>View.OnClickListener() {<br>            @Override<br>            <strong>public void </strong>onClick(View v) {<br>                presentActivity(v);<br>            }<br>        });<br>    }<br><br>    <strong>public void </strong>presentActivity(View view) {<br>        ActivityOptionsCompat options = ActivityOptionsCompat.<br>                <em>makeSceneTransitionAnimation</em>(<strong>this</strong>, view, <strong>&quot;transition&quot;</strong>);<br>        <strong>int </strong>revealX = (<strong>int</strong>) (view.getX() + view.getWidth() / 2);<br>        <strong>int </strong>revealY = (<strong>int</strong>) (view.getY() + view.getHeight() / 2);<br><br>        Intent intent = <strong>new </strong>Intent(<strong>this</strong>, SecondActivity.<strong>class</strong>);<br>        intent.putExtra(SecondActivity.<strong><em>EXTRA_CIRCULAR_REVEAL_X</em></strong>, revealX);<br>        intent.putExtra(SecondActivity.<strong><em>EXTRA_CIRCULAR_REVEAL_Y</em></strong>, revealY);<br><br>        ActivityCompat.<em>startActivity</em>(<strong>this</strong>, intent, options.toBundle());<br>    }<br>}</pre><p>Really simple, right? All we have to do is to create an scene transition animation to use the default fading animation. I am sending the coordinates to the secound activity so it knows where is it should start de reveal animation. I picked the coordinates of the center of the button, but you can choose the way you prefer.</p><p>XML for activity 2:</p><pre>&lt;<strong>RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/root_layout&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:padding=&quot;32dp&quot;<br>    android:background=&quot;@android:color/background_light&quot;<br>    android:fitsSystemWindows=&quot;true&quot;<br>    tools:context=&quot;com.ebanx.circularreveal.SecondActivity&quot;</strong>&gt;<br><br>    &lt;<strong>TextView<br>        android:text=&quot;It works!&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_centerHorizontal=&quot;true&quot; </strong>/&gt;<br><br>&lt;/<strong>RelativeLayout</strong>&gt;</pre><p>The only important line is this one:</p><pre><strong>android:background=&quot;@android:color/background_light&quot;</strong></pre><p>Our second activity has a transparent background, remember? So you need to set a color to the root_layout so you don’t end up with a totally transparent activity.</p><p>Code for activity 2:</p><p>Now we have the first part of our project. Let&#39;s make the transition between the two activities.</p><pre><strong>public class </strong>SecondActivity <strong>extends </strong>AppCompatActivity {<br><br>    <strong>public static final </strong>String <strong><em>EXTRA_CIRCULAR_REVEAL_X </em></strong>= <strong>&quot;EXTRA_CIRCULAR_REVEAL_X&quot;</strong>;<br>    <strong>public static final </strong>String <strong><em>EXTRA_CIRCULAR_REVEAL_Y </em></strong>= <strong>&quot;EXTRA_CIRCULAR_REVEAL_Y&quot;</strong>;<br><br>    View <strong>rootLayout</strong>;<br><br>    <strong>private int revealX</strong>;<br>    <strong>private int revealY</strong>;<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_second</em></strong>);<br><br>        <strong>final </strong>Intent intent = getIntent();<br><br>        <strong>rootLayout </strong>= findViewById(R.id.<strong><em>root_layout</em></strong>);<br><br>        <strong>if </strong>(savedInstanceState == <strong>null </strong>&amp;&amp; Build.VERSION.<strong><em>SDK_INT </em></strong>&gt;= Build.VERSION_CODES.<strong><em>LOLLIPOP </em></strong>&amp;&amp;<br>                intent.hasExtra(<strong><em>EXTRA_CIRCULAR_REVEAL_X</em></strong>) &amp;&amp;<br>                intent.hasExtra(<strong><em>EXTRA_CIRCULAR_REVEAL_Y</em></strong>)) {<br>               [I will show the code for this in a while!]</pre><pre>        } else {<br>                <strong>rootLayout</strong>.setVisibility(View.<strong><em>VISIBLE</em></strong>);<br>        }</pre><p>Ok, so we get the coordinates from the previous activity. But, before implementing the animation, we need to make some configurations in our project.</p><h3>Part 2 — Some configurations</h3><p>You will need to create a values-v21 folder, because the styles that you are going to use are only supported for this version and up.</p><p>Create the folder and, inside it, create a styles.xml. We are going to make the style for our first activity:</p><pre><em>&lt;!-- Base application theme. --&gt;<br></em>&lt;<strong>style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.NoActionBar&quot;</strong>&gt;<br>    <em>&lt;!-- Customize your theme here. --&gt;<br>    </em>&lt;<strong>item name=&quot;colorPrimary&quot;</strong>&gt;@color/colorPrimary&lt;/<strong>item</strong>&gt;<br>    &lt;<strong>item name=&quot;colorPrimaryDark&quot;</strong>&gt;@color/colorPrimaryDark&lt;/<strong>item</strong>&gt;<br>    &lt;<strong>item name=&quot;colorAccent&quot;</strong>&gt;@color/colorAccent&lt;/<strong>item</strong>&gt;<br>    &lt;<strong>item name=&quot;android:windowTranslucentNavigation&quot;</strong>&gt;true&lt;/<strong>item</strong>&gt;<br>    &lt;<strong>item name=&quot;android:windowTranslucentStatus&quot;</strong>&gt;true&lt;/<strong>item</strong>&gt;<br>&lt;/<strong>style</strong>&gt;<br><br>&lt;<strong>style name=&quot;AppTheme.Transparent&quot; parent=&quot;AppTheme&quot;</strong>&gt;<br>    &lt;<strong>item name=&quot;android:windowIsTranslucent&quot;</strong>&gt;true&lt;/<strong>item</strong>&gt;<br>    &lt;<strong>item name=&quot;android:windowBackground&quot;</strong>&gt;@android:color/transparent&lt;/<strong>item</strong>&gt;<br>    &lt;<strong>item name=&quot;android:windowDrawsSystemBarBackgrounds&quot;</strong>&gt;true&lt;/<strong>item</strong>&gt;<br><br>&lt;/<strong>style</strong>&gt;</pre><p>That is what makes our navigation bar, status bar and window translucent. Our windowBackground must be transparent or we won&#39;t be able to achieve the effect that we desire. When the new activity enters, we will be able to see the first activity because the second is transparent.</p><p>Apply the code theme in your activities</p><pre>&lt;<strong>activity android:name=&quot;.MainActivity&quot;<br>    android:theme=&quot;@style/AppTheme&quot;</strong>&gt;<br>    &lt;<strong>intent-filter</strong>&gt;<br>        &lt;<strong>action android:name=&quot;android.intent.action.MAIN&quot; </strong>/&gt;<br><br>        &lt;<strong>category android:name=&quot;android.intent.category.LAUNCHER&quot; </strong>/&gt;<br>    &lt;/<strong>intent-filter</strong>&gt;<br>&lt;/<strong>activity</strong>&gt;<br>&lt;<strong>activity android:name=&quot;.SecondActivity&quot;<br>    android:theme=&quot;@style/AppTheme.Transparent&quot;</strong>/&gt;</pre><h3>Part 3— The transition</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*1i61mbinnJ2129pT9w1MRw.gif" /><figcaption>Pay attention! (from giphy)</figcaption></figure><p>The animation is always the cool part. If you did everything right in the first and second part, you are going to make a nice animation is this one.</p><p>The code for the animation is in our second activity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/165dc289977e9ae14abbe43433224d28/href">https://medium.com/media/165dc289977e9ae14abbe43433224d28/href</a></iframe><p>If the smartphone is using android api 21 and above the activity will be revealed with a nice circular animation. But if it is not the case, the app still works, but the revelation is the default one.</p><p>Just in case you got confused, this is the complete code for the second activity:</p><pre><strong>public class </strong>SecondActivity <strong>extends </strong>AppCompatActivity {<br><br>    <strong>public static final </strong>String <strong><em>EXTRA_CIRCULAR_REVEAL_X </em></strong>= <strong>&quot;EXTRA_CIRCULAR_REVEAL_X&quot;</strong>;<br>    <strong>public static final </strong>String <strong><em>EXTRA_CIRCULAR_REVEAL_Y </em></strong>= <strong>&quot;EXTRA_CIRCULAR_REVEAL_Y&quot;</strong>;<br><br>    View <strong>rootLayout</strong>;<br><br>    <strong>private int revealX</strong>;<br>    <strong>private int revealY</strong>;<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_second</em></strong>);<br><br>        <strong>final </strong>Intent intent = getIntent();<br><br>        <strong>rootLayout </strong>= findViewById(R.id.<strong><em>root_layout</em></strong>);<br><br>        <strong>if </strong>(savedInstanceState == <strong>null </strong>&amp;&amp; Build.VERSION.<strong><em>SDK_INT </em></strong>&gt;= Build.VERSION_CODES.<strong><em>LOLLIPOP </em></strong>&amp;&amp;<br>                intent.hasExtra(<strong><em>EXTRA_CIRCULAR_REVEAL_X</em></strong>) &amp;&amp;<br>                intent.hasExtra(<strong><em>EXTRA_CIRCULAR_REVEAL_Y</em></strong>)) {<br>            <strong>rootLayout</strong>.setVisibility(View.<strong><em>INVISIBLE</em></strong>);<br><br>            <strong>revealX </strong>= intent.getIntExtra(<strong><em>EXTRA_CIRCULAR_REVEAL_X</em></strong>, 0);<br>            <strong>revealY </strong>= intent.getIntExtra(<strong><em>EXTRA_CIRCULAR_REVEAL_Y</em></strong>, 0);<br><br><br>            ViewTreeObserver viewTreeObserver = <strong>rootLayout</strong>.getViewTreeObserver();<br>            <strong>if </strong>(viewTreeObserver.isAlive()) {<br>                viewTreeObserver.addOnGlobalLayoutListener(<strong>new </strong>ViewTreeObserver.OnGlobalLayoutListener() {<br>                    @Override<br>                    <strong>public void </strong>onGlobalLayout() {<br>                        revealActivity(<strong>revealX</strong>, <strong>revealY</strong>);<br>                        <strong>rootLayout</strong>.getViewTreeObserver().removeOnGlobalLayoutListener(<strong>this</strong>);<br>                    }<br>                });<br>            }<br>        } <strong>else </strong>{<br>            <strong>rootLayout</strong>.setVisibility(View.<strong><em>VISIBLE</em></strong>);<br>        }<br>    }<br><br>        <strong>protected void </strong>revealActivity(<strong>int </strong>x, <strong>int </strong>y) {<br>            <strong>if </strong>(Build.VERSION.<strong><em>SDK_INT </em></strong>&gt;= Build.VERSION_CODES.<strong><em>LOLLIPOP</em></strong>) {<br>                <strong>float </strong>finalRadius = (<strong>float</strong>) (Math.<em>max</em>(<strong>rootLayout</strong>.getWidth(), <strong>rootLayout</strong>.getHeight()) * 1.1);<br><br>                <em>// create the animator for this view (the start radius is zero)<br>                </em>Animator circularReveal = ViewAnimationUtils.<em>createCircularReveal</em>(<strong>rootLayout</strong>, x, y, 0, finalRadius);<br>                circularReveal.setDuration(400);<br>                circularReveal.setInterpolator(<strong>new </strong>AccelerateInterpolator());<br><br>                <em>// make the view visible and start the animation<br>                </em><strong>rootLayout</strong>.setVisibility(View.<strong><em>VISIBLE</em></strong>);<br>                circularReveal.start();<br>            } <strong>else </strong>{<br>                finish();<br>            }<br>        }<br><br>        <strong>protected void </strong>unRevealActivity() {<br>            <strong>if </strong>(Build.VERSION.<strong><em>SDK_INT </em></strong>&lt; Build.VERSION_CODES.<strong><em>LOLLIPOP</em></strong>) {<br>                finish();<br>            } <strong>else </strong>{<br>                <strong>float </strong>finalRadius = (<strong>float</strong>) (Math.<em>max</em>(<strong>rootLayout</strong>.getWidth(), <strong>rootLayout</strong>.getHeight()) * 1.1);<br>                Animator circularReveal = ViewAnimationUtils.<em>createCircularReveal</em>(<br>                        <strong>rootLayout</strong>, <strong>revealX</strong>, <strong>revealY</strong>, finalRadius, 0);<br><br>                circularReveal.setDuration(400);<br>                circularReveal.addListener(<strong>new </strong>AnimatorListenerAdapter() {<br>                    @Override<br>                    <strong>public void </strong>onAnimationEnd(Animator animation) {<br>                        <strong>rootLayout</strong>.setVisibility(View.<strong><em>INVISIBLE</em></strong>);<br>                        finish();<br>                    }<br>                });<br><br><br>                circularReveal.start();<br>            }<br>        }<br>}</pre><p>So, this is the project that we made:</p><p>(This is a gif and the quality was reduced… The animation will look a lot better in your smartphone)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*B6I5zZV0cfp0Hen3P5bnjg.gif" /></figure><p>You can use the unRevealActivity to create the reverse animation, but I won’t put the code for this in the tutorial. I would like you to figure this out by your own (It is really easy, you got this!)</p><h3>Bonus</h3><p>You can mix the code of this tutorial and the my first one to make something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*7gnqtdDnFKDo4Zmt7LpR1g.gif" /></figure><p>And that’s it! Remember to use this animation in the right place. Avoid using it as the default transition in your app, because you are going to polute your app code with the code of this animation. But, in some specific places, this animation can the a really nice way to show the new activity.</p><p><em>If you enjoyed reading this, please click the heart icon below. This will help to share the story with others. If you would like to see more content like this one, follow me.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea6b55991f68b24354ca68fb5e19e10f/href">https://medium.com/media/ea6b55991f68b24354ca68fb5e19e10f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d94f9bfcae28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/a-little-thing-that-matter-how-to-reveal-an-activity-with-circular-revelation-d94f9bfcae28">Make your app shine #3: How to reveal an activity with circular revelation</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[Make your app shine #2: How to make a button morph into a form]]></title>
            <link>https://medium.com/android-news/make-your-app-shine-2-how-to-make-a-button-morph-into-a-form-81d2f0e6bf4a?source=rss-d7de5f017efe------2</link>
            <guid isPermaLink="false">https://medium.com/p/81d2f0e6bf4a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ui-ux]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Leandro Borges Ferreira]]></dc:creator>
            <pubDate>Tue, 09 May 2017 12:57:32 GMT</pubDate>
            <atom:updated>2017-05-22T17:09:11.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*p7yn-XmtpI7yONr1iZqExg.gif" /></figure><p>Hi folks, this is the second article of a series that I am working in to show how to make simple, but beautiful, micro interaction. You can see the first one <a href="https://android.jlelse.eu/make-your-app-shine-how-to-make-a-button-morph-into-a-loading-spinner-9efee6e39711">here</a> and the third one <a href="https://android.jlelse.eu/a-little-thing-that-matter-how-to-reveal-an-activity-with-circular-revelation-d94f9bfcae28">here</a>. The complete code of this tutorial can be found here:</p><p><a href="https://github.com/leandroBorgesFerreira/buttonMorphToFormAndroid">https://github.com/leandroBorgesFerreira/buttonMorphToFormAndroid</a></p><p>Interactions between views take some time to get good, but those are the things that make a user fall in love with your product. There is a quote about the price of design that I really like:</p><blockquote>“If you think good design is expensive, you should look at the cost of bad design.” –Ralf Speth</blockquote><p>So expend some time to get your UI polished can be a really good idea (Just don&#39;t forget to be realistic about your deadlines, ok?). So, let&#39;s learn how to make an animation that will make your users want to fill your forms.</p><h3>Part 1 — Let&#39;s make the skeleton of the project.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*tusDtIp9Q5EYKPwXVEiWpw.gif" /></figure><p>So, before make any animation we need to create our layout with the buttons and forms that are going to be animated. Let&#39;s create the XML for our first button. This is our button:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c329cf461be7f42f238f2d82c9d12951/href">https://medium.com/media/c329cf461be7f42f238f2d82c9d12951/href</a></iframe><p>You must be thinking: &quot;All of this just to create a button?? o.O&quot;. Remember that we are going to morph this button into a form, so we need to put all the views inside the button. But let&#39;s understand this layout:</p><p>1 — The CardView acts as a decorator. It gives rounded corners o the button and act as the button/form container. This is the view that is going to be animated.</p><p>2 — The button with id login_btn is the one that will listen for clicks.</p><p>3 — The LinearLayout has all the views of the form.</p><p>4 — All the views of the form are with visibility GONE. This way, for now, our form is nothing more than just a button. When the the visibility of our Views changes, we get the button with the animation at the top of this article.</p><p>So, with the views hidden, we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*LkOC4z9umvM7o-q1ZUavPA.png" /></figure><p>But if we show all the views, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*8tXlyA1NDnA7GS1pAoD5NA.png" /></figure><h3>Part 2 — The animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*TPh-jlxbyeikabRYOKo-mA.gif" /><figcaption>The is the hard part. But hang in there! From giphy</figcaption></figure><p>Now we need to make our animation. The transitions are going to be animated, so in the root view we need to insert <strong>android:animateLayoutChanges=”true”</strong>.</p><pre>&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:id=&quot;@+id/root_view&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:background=&quot;#aaa&quot;<br>    android:animateLayoutChanges=&quot;true&quot;&gt;</pre><p>We are going to make the translation animation by changing the gravity of our CardView. Did you notice that the gravity is <strong>start|bottom</strong>? If the change it to <strong>center </strong>we will see the translation animation.</p><p>Ok, so this will be out animation:</p><pre>public void morphIntoForm() {<br>        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) buttonContainer.getLayoutParams();<br><br>        initialWidth = layoutParams.width;<br>        initialGravity = layoutParams.gravity;<br><br>        layoutParams.gravity = Gravity.CENTER;<br>        layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;<br>        buttonContainer.setLayoutParams(layoutParams);<br><br>        for (int i = 1; i &lt; viewsContainer.getChildCount(); i++) {<br>                 viewsContainer.getChildAt(i).setVisibility(View.VISIBLE);<br>        }<br><br>        isPressed = true;<br>}</pre><p>Really simple, right? All we do is change the gravity and width of our buttonContainer and make all the views of the form visible.</p><p>Well, we need to declare our variable and make a reverse animation. The animation class is:</p><pre>public class MorphAnimation {<br><br>    private final FrameLayout parentView;<br>    private View buttonContainer;<br>    private ViewGroup viewsContainer;<br><br>    private boolean isPressed;<br>    private int initialWidth;<br>    private int initialGravity;<br><br>    public boolean isPressed() {<br>        return isPressed;<br>    }<br><br>    public MorphAnimation(View buttonContainer, FrameLayout parentView, ViewGroup viewsContainer) {<br>        this.buttonContainer = buttonContainer;<br>        this.parentView = parentView;<br>        this.viewsContainer = viewsContainer;<br><br>        LayoutTransition layoutTransition = parentView.getLayoutTransition();<br>        layoutTransition.setDuration(400);<br>        layoutTransition.enableTransitionType(LayoutTransition.CHANGING);<br><br>        isPressed = false;<br><br>    }<br><br>    public void morphIntoForm() {<br>        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) buttonContainer.getLayoutParams();<br><br>        initialWidth = layoutParams.width;<br>        initialGravity = layoutParams.gravity;<br><br>        layoutParams.gravity = Gravity.CENTER;<br>        layoutParams.width = FrameLayout.LayoutParams.MATCH_PARENT;<br>        buttonContainer.setLayoutParams(layoutParams);<br><br>        for (int i = 1; i &lt; viewsContainer.getChildCount(); i++) {<br>            viewsContainer.getChildAt(i).setVisibility(View.VISIBLE);<br>        }<br><br>        isPressed = true;<br>    }<br><br>    public void morphIntoButton() {<br>        for (int i = 1; i &lt; viewsContainer.getChildCount(); i++) {<br>            viewsContainer.getChildAt(i).setVisibility(View.GONE);<br>        }<br><br>        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) buttonContainer.getLayoutParams();<br>        layoutParams.gravity = initialGravity;<br>        layoutParams.width = initialWidth;<br>        buttonContainer.setLayoutParams(layoutParams);<br><br>        isPressed = false;<br>    }<br><br>}</pre><p>Besides the android:animateLayoutChanges=”true”, the also need the to <strong>setlayoutTransition.enableTransitionType(LayoutTransition.CHANGING) </strong>in our root view. This command enables the translation animation to happen. Without it, the form would simply jump to the center of the screen. You can also set the duration of the animation, like I set to 400ms.</p><p>The morphIntoButton() method is just the reversal animation of morphIntoForm().</p><h3>Part 3 — Let&#39;s call the animation!</h3><p>This is where the fun comes!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*Cg_hVf0Gio8iyPULtAcrpQ.gif" /><figcaption>From Giphy. This gif is so amazing!</figcaption></figure><p>Now all you have to do is call the animations, like this:</p><pre>public class MainActivity extends AppCompatActivity {<br><br>    private MorphAnimation morphAnimationLogin;<br>    private MorphAnimation morphAnimationRegister;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_main);<br><br>        View loginContainer = findViewById(R.id.form_btn);<br>        View registeContainer = findViewById(R.id.form_register);<br><br>        Button buttonLogin = (Button) findViewById(R.id.login_btn);<br>        Button buttonRegister = (Button) findViewById(R.id.button_register);<br><br>        ViewGroup loginViews = (ViewGroup) findViewById(R.id.login_views);<br>        ViewGroup registeViews = (ViewGroup) findViewById(R.id.register_views);<br><br>        final FrameLayout rootView = (FrameLayout) findViewById(R.id.root_view);<br><br>        morphAnimationLogin = new MorphAnimation(loginContainer, rootView, loginViews);<br>        morphAnimationRegister = new MorphAnimation(registeContainer, rootView, registeViews);<br><br>        buttonLogin.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View view) {<br>                if (!morphAnimationLogin.isPressed()) {<br>                    morphAnimationLogin.morphIntoForm();<br>                } else {<br>                    morphAnimationLogin.morphIntoButton();<br>                }<br>            }<br>        });<br><br>        buttonRegister.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                if (!morphAnimationRegister.isPressed()) {<br>                    morphAnimationRegister.morphIntoForm();<br>                } else {<br>                    morphAnimationRegister.morphIntoButton();<br>                }<br>            }<br>        });<br>    }<br>}</pre><p>I added another button in my xml to make the animation a bit more interesting. I got this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*p7yn-XmtpI7yONr1iZqExg.gif" /></figure><p>And that&#39;s it! Please remember that this animation won&#39;t work in any kind of situation, you need to adapt this tutorial to your needs. But I believe that, with some effort, you can achieve really nice interactions using this concept.</p><p><em>If you enjoyed reading this, please click the heart icon below. This will help to share the story with others. If you would like to see more content like this one, follow me.</em></p><p>Reference:</p><p>I got inspiration to make this tutorial from this <a href="https://tympanus.net/Development/ButtonComponentMorph/">site</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=81d2f0e6bf4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/make-your-app-shine-2-how-to-make-a-button-morph-into-a-form-81d2f0e6bf4a">Make your app shine #2: How to make a button morph into a form</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>