<?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 Shankar Kuppu on Medium]]></title>
        <description><![CDATA[Stories by Shankar Kuppu on Medium]]></description>
        <link>https://medium.com/@shankar.kpu?source=rss-6835330afc53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2G-_5NohPv4LoXCz.</url>
            <title>Stories by Shankar Kuppu on Medium</title>
            <link>https://medium.com/@shankar.kpu?source=rss-6835330afc53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:52:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shankar.kpu/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[How I drew custom shapes in bottom bar]]></title>
            <link>https://medium.com/@shankar.kpu/how-i-drew-custom-shapes-in-bottom-bar-85ae3ca26666?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ae3ca26666</guid>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 06:06:16 GMT</pubDate>
            <atom:updated>2019-08-01T06:06:16.117Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I received a design that contains <a href="https://developer.android.com/reference/android/support/design/widget/BottomNavigationView">BottomNavigationView</a>. Until here everything is fine, but when I looked at the sketch I said ummm… it’s going to be hard 😟. Here is a copy of the real design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*s_jZPVDR3KEVUWPn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*SMVluL5acPVRjOwu.png" /></figure><p>Curve BottomNavigationView</p><p>I’ve never did something like this before, so I started looking online on how to create a curve custom view. After some research and a discussion with my colleagues, I found out that it’s a kind of Bézier curve.</p><h3>Bézier curve</h3><p>If you’ve used a design or a drawing software, you’ve probably used Bézier curves without even knowing. This is named after a French engineer, Pierre Bézier, who invented this method to describe the smooth curves needed when designing cars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*G0B4YDfKISI0rjls" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/0*MeYLIhKxnO0ngT5J.png" /></figure><p>Bézier path in <a href="https://en.wikipedia.org/wiki/Adobe_Illustrator">Adobe Illustrator</a> (<a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve">Wikipedia</a>)</p><p>I then found a very good <a href="http://ciechanowski.me/blog/2014/02/18/drawing-bezier-curves/">article</a>that explains the type of curve I need, I strongly recommend reading it. In addition, it contains a tool to play with curves.</p><p>The type of curve that fits my design was <a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves">Cubic Bézier curves</a> and I’ll take the definition found in the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/0*gfNXzlNc4yO5kPIJ.jpeg" /></figure><p><a href="http://www.e-cartouche.ch/content_reg/cartouche/graphics/en/html/Curves_learningObject2.html">Cubic Bézier curves</a></p><p>Cubic Bézier curves are defined in terms of four control points. While the first and last control points specify locations of the endpoints of the drawn curve, the second and third control point influence the tangency of the curve.</p><p>Let’s now dive into the code and see how to create a cubic Bézier curve in Android.</p><p>First of all, we create a custom view that extends <a href="https://developer.android.com/reference/android/support/design/widget/BottomNavigationView">BottomNavigationView</a> to take advantage of all its features and just focus on the design.</p><p>If we look at the code, we’ve only added an init()method, which will just initialize the <a href="https://developer.android.com/reference/android/graphics/Path">path</a> and <a href="https://developer.android.com/reference/android/graphics/Paint">paint</a> objects.</p><p>The role of the path is to let us draw geometric forms including Bézier curve. The way path draws a line between two points : a start point and an end point. By default BottomNavigationView is in the form of a rectangle, so we’re going to use Path to redraw it with curves as shows the view above.</p><p>While path object has the role to control the styling and color of what is drawn. You can create an object just without passing a parameter, but it is possible to be more precise by specifying flags. The first thing is to determine what you want to draw, the contours of a view without its interior, or only the interior, or maybe both? In order to assign a value, we use setStyle(Paint.Style style) , For our case we will draw both contours and the interior so we’re going to use <em>FILL_AND_STROKE.</em></p><p>We can then assign a color, you choose the color you like, and you set background color of the view to transparent to avoid default color in background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*zswI8zAkcML6MBqi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*wTPUhCWLsQ76xWri.png" /></figure><p>Positions of points</p><p>First of all, we’ll initialize the positions of our points. The position of points depends on the width and height of the view. <strong>P1</strong> is the beginning point of our path this is where we will start drawing. <strong>P2</strong> is the start of our first curve. To calculate the position of the point, frankly it was a bit of trial and error using the radius of FAB button and it depends on each view and each design, so according to your needs, you can adjust these calculations. It was the same thing for <strong>P3</strong> (which is the end of the first curve and the start of the second one) and <strong>P4</strong> (the end of the second curve).</p><p><strong>Avoid doing calculations in the </strong><strong>onDraw()method because it is called each time and it is not good for the performance of your application. </strong>I made the calculations of my point in the onSizeChanged() method which is called when the size of the view has changed, so not too greedy in terms of performance</p><p>Now here is the most interesting and complicated part . No no, don’t worry it’s easier than you think. To begin we reset the path to clear any lines and curves from it, then we move it to the beginning point <strong>P1 </strong>using moveTo(x,y)method and draw the first line which is between <strong>P1</strong> and <strong>P2</strong>using lineTo(x,y)that adds a line from the last point to the specified point, and to clarify, in our case we do not really need to specify the beginning point because by default If there is no previous point, then a moveTo(0,0)is inserted automatically.</p><p>For the cubic curves, we gonna use cubicTo(x1,y1,x2,y2,x3,y3)method which allows us to draw a cubic curve, so the first and second point <em>(x1,y1) (x2,y2) </em>have the role of controlling the tangency. For the calculations, as you might have guessed, you have to try and grope to have the right position for your control points. To have an idea where the control points can be positioned you can try this online <a href="http://ciechanowski.me/blog/2014/02/18/drawing-bezier-curves/">tool</a> . We do the same thing for the second curve, and finally, we draw the rest of the navigation bar as if we draw a rectangle using lineTo and close the contour.</p><p>Finally, we will be able to paint using the <a href="https://developer.android.com/reference/android/graphics/Canvas">canvas</a> object which is the component on which we will paint. Canvas offers several drawing methods and the one that suits our use case is canvas.drawPath(Path path, Paint paint) that according to the documentation draws the specified path using the specified paint and the path will be filled or framed based on the Style in the paint.</p><p>Now I hope it’s clearer for you how to draw with android and how to have bezier curve. Happy coding</p><h3>References</h3><p>You can find sample code in my <a href="https://github.com/IslamBesto/CustomBottoBar/tree/java">Github</a> in both langage Java/Kotlin. You need just to checkout to the concerned branch</p><h3><a href="https://github.com/IslamBesto/CustomBottoBar/tree/java?source=post_page---------------------------">IslamBesto/CustomBottoBar</a></h3><h3><a href="https://github.com/IslamBesto/CustomBottoBar/tree/java?source=post_page---------------------------">Contribute to IslamBesto/CustomBottoBar development by creating an account on GitHub.</a></h3><h4><a href="https://github.com/IslamBesto/CustomBottoBar/tree/java?source=post_page---------------------------">github.com</a></h4><h3><a href="http://ciechanowski.me/blog/2014/02/18/drawing-bezier-curves/?source=post_page---------------------------">Drawing Bézier Curves</a></h3><h3><a href="http://ciechanowski.me/blog/2014/02/18/drawing-bezier-curves/?source=post_page---------------------------">A few months ago I’ve released my latest iPad app — Revolved. The core idea of Revolved is super simple — you draw…</a></h3><h4><a href="http://ciechanowski.me/blog/2014/02/18/drawing-bezier-curves/?source=post_page---------------------------">ciechanowski.me</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ae3ca26666" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Right Way to create Splash Screen on Android]]></title>
            <link>https://medium.com/@shankar.kpu/right-way-to-create-splash-screen-on-android-f10991de86cc?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/f10991de86cc</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Thu, 19 Apr 2018 05:23:47 GMT</pubDate>
            <atom:updated>2018-04-19T05:23:47.223Z</atom:updated>
            <content:encoded><![CDATA[<p>As we all know splash screen is the user’s first experience of your application. It normally used to display some kind of progress before the application setup completely. As per Google material design spec, Splash Screen follows a pattern known called Launch Screen. You can find the specification <a href="https://material.io/guidelines/patterns/launch-screens.html">here</a>.</p><h3>Common Mistake</h3><p>In most of the application developers use splash screen to showcase brand icon or picture for couple of seconds. This is common practice which most of the developers are following. It is not a good idea to use a splash screen that wastes a user’s time. This should be strictly avoided.</p><p>With the common approach you may also lead the <strong>problem of blank white page appears</strong> during splash launching.</p><h3>Right Way</h3><p>The right way of implementing a splash screen is a little different. In the new approach specify your splash screen’s background as the activity’s theme background.</p><p>Also the root cause of blank white page problem is that your layout file is visible only after app has been initialized completely.</p><p>Do not create a layout file for splash activity. Instead, specify activity’s theme background as splash layout.</p><h3>Implementation</h3><p>To implement above approach, first create an XML drawable <em>splash_background.xml</em> inside <em>res/drawable</em> folder:</p><pre><em>&lt;?</em><strong>xml version=”1.0&quot; encoding=”utf-8&quot;</strong><em>?&gt;<br> </em>&lt;<strong>layer-list xmlns:android=”http://schemas.android.com/apk/res/android&quot;</strong>&gt;<br> <br> &lt;<strong>item android:drawable=”@color/colorPrimary” </strong>/&gt;<br> <br> &lt;<strong>item</strong>&gt;<br> &lt;<strong>bitmap<br> android:gravity=”center”<br> android:src=”@mipmap/ic_launcher” </strong>/&gt;<br> &lt;/<strong>item</strong>&gt;<br> <br>&lt;/<strong>layer-list</strong>&gt;</pre><p>In the next step, set <em>splash_background.xml</em> as your splash activity’s background in the theme. Add a new <em>SplashTheme </em>for your splash activity:</p><pre>&lt;<strong>resources</strong>&gt;</pre><pre><em>&lt;!-- Base application theme. --&gt;</em></pre><pre>&lt;<strong>style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.DarkActionBar&quot;</strong>&gt;</pre><pre><em>&lt;!-- Customize your theme here. --&gt;</em></pre><pre>&lt;<strong>item name=&quot;colorPrimary&quot;</strong>&gt;@color/colorPrimary&lt;/<strong>item</strong>&gt;</pre><pre>&lt;<strong>item name=&quot;colorPrimaryDark&quot;</strong>&gt;@color/colorPrimaryDark&lt;/<strong>item</strong>&gt;</pre><pre>&lt;<strong>item name=&quot;colorAccent&quot;</strong>&gt;@color/colorAccent&lt;/<strong>item</strong>&gt;</pre><pre>&lt;/<strong>style</strong>&gt;</pre><pre><em>&lt;!-- Splash Screen theme. --&gt;</em></pre><pre>&lt;<strong>style name=&quot;SplashTheme&quot; parent=&quot;Theme.AppCompat.NoActionBar&quot;</strong>&gt;</pre><pre>&lt;<strong>item name=&quot;android:windowBackground&quot;</strong>&gt;@drawable/splash_background&lt;/<strong>item</strong>&gt;</pre><pre>&lt;/<strong>style</strong>&gt;</pre><pre>&lt;/<strong>resources</strong>&gt;</pre><p>Configure <em>SplashTheme </em>as your splash activity’s theme in your <em>AndroidManifest.xml</em>:</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;</em></pre><pre>&lt;<strong>manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</strong></pre><pre><strong>package=&quot;com.androidjavapoint.splashscreen&quot;</strong>&gt;</pre><pre>&lt;<strong>application</strong></pre><pre><strong>android:allowBackup=&quot;true&quot;</strong></pre><pre><strong>android:icon=&quot;@mipmap/ic_launcher&quot;</strong></pre><pre><strong>android:label=&quot;@string/app_name&quot;</strong></pre><pre><strong>android:supportsRtl=&quot;true&quot;</strong></pre><pre><strong>android:theme=&quot;@style/AppTheme&quot;</strong>&gt;</pre><pre>&lt;<strong>activity</strong></pre><pre><strong>android:name=&quot;.SplashActivity&quot;</strong></pre><pre><strong>android:theme=&quot;@style/SplashTheme&quot;</strong>&gt;</pre><pre>&lt;<strong>intent-filter</strong>&gt;</pre><pre>&lt;<strong>action android:name=&quot;android.intent.action.MAIN&quot; </strong>/&gt;</pre><pre>&lt;<strong>category android:name=&quot;android.intent.category.LAUNCHER&quot; </strong>/&gt;</pre><pre>&lt;/<strong>intent-filter</strong>&gt;</pre><pre>&lt;/<strong>activity</strong>&gt;</pre><pre>&lt;<strong>activity android:name=&quot;.HomeActivity&quot; </strong>/&gt;</pre><pre>&lt;/<strong>application</strong>&gt;</pre><pre>&lt;/<strong>manifest</strong>&gt;</pre><p>Create an empty activity for Splash without XML layout file. This class will simply redirect to home activity.</p><pre><strong>package </strong>com.androidjavapoint.splashscreen;</pre><pre><strong>import </strong>android.content.Intent;</pre><pre><strong>import </strong>android.os.Bundle;</pre><pre><strong>import </strong>android.support.v7.app.AppCompatActivity;</pre><pre><strong>public class </strong>SplashActivity <strong>extends </strong>AppCompatActivity {</pre><pre>@Override</pre><pre><strong>protected void </strong>onCreate(Bundle savedInstanceState) {</pre><pre><strong>super</strong>.onCreate(savedInstanceState);</pre><pre><em>// Start home activity</em></pre><pre>startActivity(<strong>new </strong>Intent(SplashActivity.<strong>this</strong>, HomeActivity.<strong>class</strong>));</pre><pre><em>// close splash activity</em></pre><pre>finish();</pre><pre>}</pre><pre>}</pre><p>Notice that we do not have <em>setContentView()</em> for this SplashActivity. View is displaying from the theme and this way it is faster than creating a layout.</p><p>If you look at the time splash screen displays is exactly the same with the time taken by app to configure itself because of a cold launch (very first launch). If the app is cached, the splash screen will go away almost immediately.</p><p>Hope using this article you will be able make your splash screen work in a right way.</p><p>All the code explained is available on <a href="https://github.com/AnkitSinhal/SplashScreen">GitHub</a>.</p><p>Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.</p><p>Check out my blogger page for more interesting topics on Software development at <a href="http://androidjavapoint.blogspot.in/">http://androidjavapoint.blogspot.in</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f10991de86cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anko layouts on Android. Should I forget about XMLs?]]></title>
            <link>https://medium.com/@shankar.kpu/anko-layouts-on-android-should-i-forget-about-xmls-92f795b3f5f2?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f795b3f5f2</guid>
            <category><![CDATA[anko]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Thu, 19 Apr 2018 05:22:06 GMT</pubDate>
            <atom:updated>2018-04-19T05:22:06.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*Y1cXHdt1bvqulgaA.jpg" /></figure><p>If you’re already developing Android Apps using Kotlin, you’re probably heard about Anko layouts and been thinking about using them, or at least considering to take a look at them.</p><p>The truth is that <a href="https://github.com/Kotlin/anko/">Anko</a> has been around for really long. In fact, when I started writing <a href="https://antonioleiva.com/book/">my book about Kotlin on Android</a> at the beginning of 2015, this library already existed.</p><p>But in case you hadn’t heard about it, Anko is a library <strong>developed by the Kotlin</strong> team with the goal of <strong>simplifying the interaction with the Android framework</strong>.</p><p>Its most outstanding feature is Anko layouts, which I’ll talk about in this article. But it also has others such as small DSL to <a href="https://antonioleiva.com/anko-background-kotlin-android/">execute asynchronous tasks</a> in a very simple way, another one to build <a href="https://antonioleiva.com/dialogs-android-anko-kotlin/">easy dialogs and alerts</a>, a set of functions to <a href="https://antonioleiva.com/databases-anko-kotlin/">deal with SQLite</a>, and even an <a href="https://android.jlelse.eu/a-first-walk-into-kotlin-coroutines-on-android-fe4a6e25f46a">implementation of coroutines</a>, among many other things</p><p>I must admit that I’m a huge fan of this library, because it has a lot of awesome features and it’s been really helpful to me to understand Kotlin and how to apply it to Android development.</p><p>But there’s something in this library that always pushed me back: <strong>Anko layouts DSL</strong>.</p><h3>Anko layouts DSL</h3><p>The idea of Anko layouts is to take the most out of Kotlin to provide a DSL that <strong>makes declaring Android layouts easy and powerful, just by getting rid of the XMLs</strong>.</p><p>I’ve been developing Android Apps for like 6 years, and I’m really fluent with XMLs already. So when I tried to do something with Anko layouts, it was like starting from scratch to me.</p><p>But for simple examples, it looked really powerful! I could write a small login form in a breeze. With just this code:</p><p>UI(true) {</p><p>verticalLayout {</p><p>val user = editText {</p><p>hint = “Username”</p><p>}</p><p>val pass = editText {</p><p>hint = “Password”</p><p>}</p><p>button(“Login”) {</p><p>setOnClickListener {</p><p>longToast(“User: ${user.text}, Pass: ${pass.text}”)</p><p>}</p><p>}</p><p>}</p><p>}</p><p>I’d get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*cF0K_k1xBAJaAgWk.jpg" /></figure><p>Pretty awesome, right?</p><p>But we all know that small samples are never enough to get the whole picture, so I decided to convert my whole <a href="https://github.com/antoniolg/Bandhook-Kotlin/">Bandhook-Kotlin repo</a> views to Anko layouts. And based on this experience, I decided to write this article</p><h3>Should I start using Anko layouts to build my projects?</h3><p>Mimicking the structure I used in the <a href="https://antonioleiva.com/kotlin-dsl-gradle/">Kotlin DSL</a> article, I will start by trying to answer this question.</p><p>In this case it’s not so black or white. Based on my short experience, <strong>I wouldn’t use it instead of XML</strong>. These are the pros and cons I found:</p><p>Pros:</p><ul><li>It’s <strong>really easy to start with it</strong>: the DSL is really intuitive for simple examples, and the code you need to write is clean and nice to read.</li><li>It skips the inflation step, so the<strong> views written with Anko are much faster to initialize</strong> that those written in XML. There are some articles like <a href="https://android.jlelse.eu/400-faster-layouts-with-anko-da17f32c45dd">this from Simon Vergauwen</a> that show it’s even 4 times faster.</li><li>Using Kotlin code means you can do more complex things: for instance set a dimension that is the sum of two dimensions, <strong>simpler data binding, views are easier to reuse and compose</strong>…</li></ul><p>But these are the cons I found:</p><ul><li><strong>You need to start learning from scratch</strong>: new API, new rules. So, at the beginning, you’ll find some things much more difficult to do that just by using XML. This shouldn’t be a stopper though.</li><li>There are things that are inherently more complex, like styling your views, setting layout params.</li><li><strong>You need to write your views blindly</strong>. You don’t have a powerful designer to implement the view, or at least see the view you’re writing. That’s half-true, because there’s a plugin that should show a preview, but I’ve never seen it working, it’s broken quite often. You cannot use tools: attributes either, which are very useful when doing layouts.</li><li>Some things may be even impossible. There XML properties that sometimes don’t have their equivalent in Java, so you can’t do much here.</li></ul><p>In general,<strong> I’d encourage you to try it and take your own decisions</strong>. I know of people that love Anko layouts, and can understand why.</p><p>I can find a very good use case for simple layouts like custom views for dialogs, or adapter views.</p><h3>How to start using Anko</h3><p>For a full reference, I recommend you to<a href="https://github.com/antoniolg/Bandhook-Kotlin/"> take a look at the repository</a>, but I’ll tell you here some steps that will help you follow the code.</p><h3>Add the corresponding dependencies</h3><p>Anko is split into several libraries, so that you add only what you need. For views, the base one is this:</p><h4><strong>implementation “org.jetbrains.anko:anko-sdk19:$anko_version”</strong></h4><p>The SDK you use should correspond to the minimum version you support (or previous). There’s sdk-15, sdk-19, sdk-21, sdk-23and sdk-25.</p><p>So let’s say your minSDK is 17, you should use sdk-15.</p><p>Then, depending on what other support libraries you use, you will add the corresponding Anko one:</p><p><strong>implementation “org.jetbrains.anko:anko-appcompat-v7:$anko_version”</strong></p><p>And there are others for design library, cardview, etc. The complete reference <a href="https://github.com/Kotlin/anko/">is at Anko repository</a>.</p><h3>The base activity</h3><p>You can just do a UI block as I did in the example above, but this can make your activity grow fast. It’s better to have the layout in another class.</p><p>So for this, I created a base activity, which will force to declare the property that holds the layout:</p><p>abstract class BaseActivity&lt;out UI : ActivityAnkoComponent&lt;out AppCompatActivity&gt;&gt;</p><p>: AppCompatActivity() {</p><p>abstract val ui: UI</p><p>override fun onCreate(savedInstanceState: Bundle?) {</p><p>super.onCreate(savedInstanceState)</p><p>(ui as ActivityAnkoComponent&lt;AppCompatActivity&gt;).setContentView(this)</p><p>setSupportActionBar(ui.toolbar)</p><p>}</p><p>}</p><p>In onCreate, it sets the view from the property as the view of the activity, and also uses the toolbar from this layout.</p><p>The generic type of the activity is just an interface that forces implementers to hold a reference to the toolbar:</p><p><strong>interface ActivityAnkoComponent&lt;T : AppCompatActivity&gt; : AnkoComponent&lt;T&gt; {</strong></p><p><strong>val toolbar: Toolbar</strong></p><p><strong>}</strong></p><p>That way, the activity can use it in onCreate.</p><h3>Building the layout</h3><p>Each activity holds an ActivityAnkoComponent, that will be the one in charge to build the activity. Here’s when we’ll use Anko layouts:</p><p>override fun createView(ui: AnkoContext&lt;MainActivity&gt;) = with(ui) {</p><p>coordinatorLayout {</p><p>appBarLayout {</p><p>toolbar = themedToolbar(R.style.ThemeOverlay_AppCompat_Dark_ActionBar) {</p><p>backgroundResource = R.color.primary</p><p>}.lparams(width = matchParent) {</p><p>scrollFlags = SCROLL_FLAG_SNAP or SCROLL_FLAG_SCROLL or SCROLL_FLAG_ENTER_ALWAYS</p><p>}</p><p>}.lparams(width = matchParent)</p><p>recycler = autoFitRecycler()</p><p>.apply(AutofitRecyclerView::style)</p><p>.lparams(matchParent, matchParent) {</p><p>behavior = AppBarLayout.ScrollingViewBehavior()</p><p>}</p><p>}</p><p>}</p><p>As you can see, the parent class is a <a href="https://antonioleiva.com/coordinator-layout/">CoordinatorLayout</a>, which holds an AppBarLayout with a Toolbar, and a <a href="https://antonioleiva.com/recyclerview/">RecyclerView</a>.</p><p>An interesting thing is how the layout params are declared. It’s a function where you set width and height by argument (default is WRAP_CONTENT), and then a block to add the rest of extra parameters:</p><p>.lparams(matchParent, matchParent) {</p><p>behavior = AppBarLayout.ScrollingViewBehavior()</p><p>}</p><h3>Use custom views</h3><p>By default, we only have functions for framework and support libraries views, but you can create you own. For instance, in the example above I created autoFitRecycler:</p><p>fun ViewManager.autoFitRecycler(theme: Int = 0) = autoFitRecycler(theme) {}</p><p>inline fun ViewManager.autoFitRecycler(theme: Int = 0, init: AutofitRecyclerView.() -&gt; Unit)</p><p>= ankoView(::AutofitRecyclerView, theme, init)</p><p>You can know more about this at the <a href="https://github.com/Kotlin/anko/wiki/Anko-Layouts#is-it-extensible">repository wiki</a>.</p><h3>Applying styles</h3><p>For each view, there exists a themed version that allows you to apply a theme, such as the toolbar here:</p><p>toolbar = themedToolbar(R.style.ThemeOverlay_AppCompat_Dark_ActionBar)</p><p>But, if what you want is to apply a style, you cannot use an XML one. Instead, you need to use the functions apply or applyRecursively. This second one, in case you want to apply the style also to the sub-views:</p><p>.applyRecursively { view -&gt;</p><p>when (view) {</p><p>is EditText -&gt; view.textSize = 18f</p><p>}</p><p>}</p><p>As a way to extract styles, I implemented this extension function for the recycler:</p><p>fun AutofitRecyclerView.style() {</p><p>clipToPadding = false</p><p>columnWidth = dimen(R.dimen.column_width)</p><p>scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY</p><p>horizontalPadding = dimen(R.dimen.recycler_spacing)</p><p>verticalPadding = dip(2)</p><p>addItemDecoration(PaddingItemDecoration(dip(2)))</p><p>}</p><p>I can then apply the style this way:</p><p>recycler = autoFitRecycler()</p><p>.apply(AutofitRecyclerView::style)</p><p>And these are basically the rough edges you need to know to understand the code.</p><p>There are some more complex views, which uses a an AppBarLayoutwith a <a href="https://antonioleiva.com/collapsing-toolbar-layout/">CollapsingToolbarLayout</a>, which holds an ImageView, a Toolbar and a TabLayout. Then the main area is using a ViewPager. I’m leaving the code here for a reference on how it looks:</p><p>coordinatorLayout {</p><p>themedAppBarLayout(R.style.ThemeOverlay_AppCompat_Dark_ActionBar) {</p><p>fitsSystemWindows = true</p><p>collapsingToolbarLayout = collapsingToolbarLayout {</p><p>fitsSystemWindows = true</p><p>collapsedTitleGravity = Gravity.TOP</p><p>expandedTitleMarginBottom = dip(60)</p><p>image = squareImageView {</p><p>fitsSystemWindows = true</p><p>}.lparamsC(matchParent) {</p><p>collapseMode = COLLAPSE_MODE_PARALLAX</p><p>}</p><p>toolbar = toolbar {</p><p>popupTheme = R.style.ThemeOverlay_AppCompat_Light</p><p>titleMarginTop = dip(16)</p><p>}.lparamsC(width = matchParent, height = dip(88)) {</p><p>gravity = Gravity.TOP</p><p>collapseMode = COLLAPSE_MODE_PIN</p><p>}</p><p>tabLayout = tabLayout {</p><p>setSelectedTabIndicatorColor(Color.WHITE)</p><p>}.lparamsC(width = matchParent) {</p><p>gravity = Gravity.BOTTOM</p><p>}</p><p>}.lparams(width = matchParent) {</p><p>scrollFlags = SCROLL_FLAG_SCROLL or SCROLL_FLAG_EXIT_UNTIL_COLLAPSED</p><p>}</p><p>}.lparams(width = matchParent)</p><p>viewPager = viewPager {</p><p>id = View.generateViewId()</p><p>}.lparams {</p><p>behavior = AppBarLayout.ScrollingViewBehavior()</p><p>}</p><p>}</p><h3>Kotlin and Anko Layouts, an interesting combination</h3><p>It’s true that working with this DSL is quite fun, and when you overcome the first part of the learning curve, you’ll probably enjoy it.</p><p>My experience with it was good at the beginning, <strong>but not so much when I started doing some more complex things</strong>. The worst part for me is not having a good preview I can rely on.</p><p>For instance, I have a problem with the artists layout, and it’s really difficult to fix just by compiling and running all the time.</p><p>But as I said, it’s probably that I haven’t spent enough time playing with it. So <strong>try it before making a decision</strong>.</p><p>And if you’re an Anko lover, please shout in the comments and tell us why! I’ll be happy to learn from your experience</p><p>Remember there’s a full example at <a href="https://github.com/antoniolg/Bandhook-Kotlin/">Bandhook-Kotlin repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f795b3f5f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[25 new Android libraries, projects and tools worthy to check in Spring 2018]]></title>
            <link>https://medium.com/@shankar.kpu/25-new-android-libraries-projects-and-tools-worthy-to-check-in-spring-2018-578f0c32ad25?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/578f0c32ad25</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Tue, 17 Apr 2018 06:16:56 GMT</pubDate>
            <atom:updated>2018-04-17T12:01:41.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*IsJ5TglZYaj8aqLjfXVzTA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/f39ab9Rrx0Q?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">chuttersnap</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is a list of 25 newest Android libraries, projects and tools released in past 3 months. All of them are my personal choice. They are not in the ranked order. Definitely worthy to check and be included in your project or just play with them and have a lot of fun. Enjoy!</p><p><strong>1.</strong><a href="https://github.com/Genymobile/scrcpy"><strong> scrcpy</strong></a></p><p>Let’s get off to a good start with scrcpy! This tool is developed by <a href="https://medium.com/@Genymotion">Genymotion</a> team and does exactly the same what <a href="https://www.vysor.io/">Vysor</a> does (if you’re not familiar with this tool, you can check my article about <a href="https://hackernoon.com/10-tools-which-will-boost-your-android-productivity-and-hype-bea88e0bcd86">10 useful tools for Android Developers</a>).<br>It provides display and control of Android devices connected on USB. It does not require any <em>root</em> access. It works on <em>GNU/Linux</em>, <em>Windows</em> and <em>MacOS </em>and it is for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*HlmlaSQz2osUG2yHoHzy8A.png" /></figure><p><em>README</em> is really comprehensive and well-written. It includes how to install and build the project. For Mac users the project is available via homebrew as well. I personally built and installed the project on my own and I can confirm, it works like a charm. I recommend this tool in 100%.</p><p><a href="https://github.com/harjot-oberai/Long-Shadows"><strong>2. Long Shadows</strong></a></p><p>This is a library for efficiently generating and rendering beautiful long shadows in Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Zcuyf2o4gLDvIQ4nkPwyTA.png" /></figure><p>This library include many features like for instance:</p><ul><li>Supporting any type of View,</li><li>allowing to a precise control over shadows on every View,</li><li>multiple shadows for a View,</li><li>shadow animations,</li><li>async calculations and many more.</li></ul><p><em>README </em>is full of great examples and really well-written. It is probably one of the best <em>README</em> I have ever read. <br>The project is released under MIT license.</p><p><strong>3. </strong><a href="https://github.com/totond/TextPathView"><strong>TextPathView</strong></a></p><p>This is a view with text path animation. One gif is more than thousand words, so check it below!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FdPoQ3GSxQ0yzBIDnLgAJg.gif" /></figure><p>The original <em>README</em> is in Chinese, but there is also an <a href="https://github.com/totond/TextPathView/blob/master/README-en.md">English version</a>. It provides vital information how to use the library, what are the newest updates and what is in the pipeline. Bare in mind, that it is in an early stage of development (version 0.1.2).<br>The project is released under MIT license.</p><p><strong>4. </strong><a href="https://github.com/florent37/ShapeOfView"><strong>ShapeOfView</strong></a></p><p>This is a library which allows to add a custom shape to of Android Views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7Vb4pJh4fH9sKDp-pZHTow.png" /></figure><p>This is also an example, what can be built using the library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*emAxASRzBMCeA_WDLxHXyA.gif" /></figure><p>Pretty impressive, huh? The documentation is really useful in terms of examples. You will find there many readymade samples. The library itself is realised under Apache 2.0 license.</p><p><strong>5. </strong><a href="https://github.com/Commit451/ModalBottomSheetDialogFragment"><strong>ModalBottomSheetDialogFragment</strong></a></p><p>This library was developed to use Modal bottom sheet dialog based on the <a href="https://material.io/guidelines/components/bottom-sheets.html#bottom-sheets-modal-bottom-sheets">Material Guidelines</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*S14vbY4_gZQVsv4C4KWdrA.png" /></figure><p>The documentation is sufficient enough to start using the dialogs. The project itself is released under Apache 2.0 license.</p><p><strong>6. </strong><a href="https://github.com/burhanrashid52/PhotoEditor"><strong>PhotoEditor</strong></a></p><blockquote>A Photo Editor library with simple, easy support for image editing using paints, text, emoji and sticker like stories.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*nYr0qz-D87DINr6AmDA54g.gif" /></figure><p>It supports:</p><ul><li>Drawing on image with an option to change a brush’s color, size and opacity,</li><li>erasing,</li><li>adding / editing text with options to change its color and fonts,</li><li>adding stickers and images,</li><li>deleting, saving and many more.</li></ul><p>The <em>README </em>is comprehensive and definitely worthy to check. The project is in quite early stage with version 0.1.1 and released under Apache 2.0 license.</p><p><strong>7. </strong><a href="https://github.com/willowtreeapps/Hyperion-Android"><strong>Hyperion-Android</strong></a></p><p>Hyperion is an app debugging and inspection tool. Made as</p><blockquote>a hidden plugin drawer that can easily be integrated into any app.</blockquote><blockquote>The drawer sits discreetly under the app so that it is there when you need it and out of the way when you don’t. Hyperion plugins are designed to make inspection of your app quick and simple.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*pNYyldz2pqjwpKuyE5Chgg.gif" /></figure><p>For further information you should check <a href="https://github.com/willowtreeapps/Hyperion-Android"><em>README</em></a><em> </em>and a <a href="https://willowtreeapps.com/ideas/introducing-hyperion-for-android">blog post.</a><br>The project is released under MIT license and currently it has version 0.9.22.</p><p><strong>8. </strong><a href="https://github.com/florent37/KotlinPleaseAnimate"><strong>KotlinPleaseAnimate</strong></a></p><p>This is a library written in Kotlin to declare and run beautiful animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*uYbrHNhhPTOd6nrZTDMBdg.gif" /></figure><p>The documentation is sufficient to start playing with it.<br>The project is released under Apache 2.0 license.</p><p><strong>9. </strong><a href="https://github.com/qhutch/ElevationImageView"><strong>ElevationImageView</strong></a></p><p>Thanks to this library you will be able to add an elevation shadow to you ImageView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*m4hQ9-esJkERxqFadiGTqA.gif" /></figure><p>A documentation is quite short but it is enough to start. Currently, there is a version 1.1 and the project is released under Apache 2.0 license.</p><p><strong>10. </strong><a href="https://github.com/leinardi/FloatingActionButtonSpeedDial"><strong>Floating Action Button Speed Dial</strong></a></p><p>This is a library which provides an implementation of the <a href="https://material.io/guidelines/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions">Material Design Floating Action Button Speed Dial</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EHNBlhGi8gM5PSc8HamcxA.gif" /></figure><p>The documentation is really comprehensive and includes also a <a href="https://play.google.com/store/apps/details?id=com.leinardi.android.speeddial.sample">sample app</a> available in Google Play.<br>The project is released under Apache 2.0 license.</p><p><strong>11. </strong><a href="https://github.com/alexstyl/RadiusTransition"><strong>RadiusTransition</strong></a></p><p>This is an app which is a showcase of how to <a href="https://developer.android.com/training/transitions/custom-transitions.html">transition</a> between a circular image to a square one across activities. The image in this example is fetched via <a href="https://github.com/bumptech/glide">Glide</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XKAvYA42bY4uXNcmyQ4dnw.gif" /></figure><p>The <em>README</em> is short but you can always check code, as it is quite straightforward. There is no mention about a license.</p><p><strong>12. </strong><a href="https://github.com/JorgeCastilloPrz/hiroaki"><strong>hiroaki</strong></a></p><blockquote>The intention of Hiroaki is to achieve clarity on your API integration tests in an idiomatic way by leveraging the power of Kotlin.</blockquote><blockquote>It uses <em>MockWebServer</em> to provide a mock server as a target for your HTTP requests that you&#39;ll use to mock your backend.</blockquote><blockquote>That enables you to assert over how your program reacts to some predefined server &amp; API behaviors.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Jyvmh03K8Y1AwJmypQEzLg.png" /></figure><p>The documentation is really comprehensive and definitely worthy to check. The project is written under Apache 2.0 license.</p><p><strong>13. </strong><a href="https://github.com/iglaweb/Ferris-Wheel"><strong>Ferris-Wheel</strong></a></p><p>Many of you probably heard about London Eye. It is a one of the world’s tallest Ferris wheel. Now you can have your own Ferris wheel in your application thanks to <a href="https://github.com/iglaweb/Ferris-Wheel">Ferris-Wheel</a> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*C-LgYzzqtQoDomgdEfKkew.gif" /></figure><p>In the <em>README</em> you can check how to include and use it in your project. It is released under Apache 2.0 license.</p><p><strong>14. </strong><a href="https://github.com/vanniktech/gradle-dependency-graph-generator-plugin"><strong>gradle-dependency-graph-generator-plugin</strong></a></p><p>This is a Gradle plugin that lets you visualize your dependencies form a project in a graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*A4TTHO0JiWxa6L-eik0Ycg.png" /></figure><p>In the documentation you can find how to set up the plugin and how to use it. <br>The project is written under Apache 2.0 license.</p><p><strong>15. </strong><a href="https://github.com/florent37/RuntimePermission"><strong>Runtime Permission</strong></a></p><p>This library is, according to <a href="https://medium.com/@florentchampigny">Florent Champigny</a>, the simpliest way to ask for runtime permissions on Android. We can choose our own way using:</p><ul><li>Kotlin</li><li>Kotlin with Coroutines</li><li>RxJava</li><li>Java8</li><li>Java7</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*n6RxH-GcXE8TJgZGpGQ15Q.png" /></figure><p>For more information check the documentation. The project is released under Apache 2.0 license.</p><p><strong>16. </strong><a href="https://github.com/StylingAndroid/Prefekt"><strong>Prefekt</strong></a></p><blockquote>Prefekt is an Android SharedPreferences library for Kotlin. It is typesafe, easy to consume, and efficient thanks to in-memory caching. You can subscribe for updates so that if the underlying SharedPreference value is changed you receive a callback even if the change was made directly to the SharedPreference value is changed outside of Prefekt.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xPmj6q0kdkc6VaCevPObuA.png" /></figure><p>According to the author, there are some interesting features in the pipeline so we should watch this project, which is released under Apache 2.0 license.</p><p><strong>17. </strong><a href="https://github.com/skydoves/ColorPickerPreference"><strong>ColorPickerPreference</strong></a></p><p>A library that let you implement ColorPickerView, ColorPickerDialog and ColorPickerPreference. It can also get HSV color, RGB values, HTML color code from your gallery pictures or custom images just by touching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yZ2buACzMoPgdmWOiLovPg.gif" /></figure><p>The documentation is really comprehensive and contains even methods descriptions. Definitely worthy to check.<br>License: Apache 2.0</p><p><strong>18. </strong><a href="https://github.com/nekocode/MusicVisualization"><strong>MusicVisualization</strong></a></p><blockquote>This project ports some music visulization shaders from <a href="http://shadertoy.com/">WebGL</a> to Android OpenGL ES. It captures the audio’s fft &amp; waveform data by system’s <a href="https://developer.android.com/reference/android/media/audiofx/Visualizer.html"><em>Visualizer</em></a>, and then pass them to a 2-lines height texture that can be used in a shader program.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*g-rhheU_dQDu3Yg0wCH0-A.png" /></figure><p>There is also sample apk available in <a href="https://github.com/nekocode/MusicVisualization/releases">release page</a>.<br>The project is released under Apache 2.0 license.</p><p><strong>19. </strong><a href="https://github.com/Team-Blox/TreeView"><strong>TreeView</strong></a></p><blockquote>Android TreeView is used to display data in tree structures. <br>The library is designed to support different algorithms. Currently, only the algorithm from Walker (with the runtime improvements from Buchheim) has been implemented.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*n0kI0VAIiaaheetiTVtfIw.png" /></figure><p>The documentation is comprehensive and provides vital steps to include the library to Android project. <br>License: Apache 2.0</p><p><strong>20. </strong><a href="https://github.com/flipkart-incubator/inline-youtube-view"><strong>inline-youtube-view</strong></a></p><p>This is an utility library for using YouTube inside your Android app. The YouTube component was developed to work with Android, iOS and React Native.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*UQV5cJhqTBA70xG1nCuhzA.gif" /></figure><p>The library addresses some problems and challenges which come with facts that:</p><ul><li>YouTube SDK does not work on all devices (where YouTube services could have been uninstalled),</li><li>we cannot run more than one instance of the YouTube view,</li><li>it is problematic to play multiple videos inline in a single list.</li></ul><p>More in the <a href="https://github.com/flipkart-incubator/inline-youtube-view">documentation</a>. There is no mention about a license.</p><p><strong>21. </strong><a href="https://github.com/TonnyL/WhatsNew"><strong>WhatsNew</strong></a></p><p>WhatsNew automatically displays a short description of the new features (in a DialogFragment)when users update your app. Inspired by <a href="https://github.com/BalestraPatrick/WhatsNew">WhatsNew</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*PlHJphfrNMAhCt97su3l-g.png" /></figure><p>In the <em>README</em> you can check how to apply it. The project is released under MIT license.</p><p><strong>22. </strong><a href="https://github.com/armcha/ColoredShadowImageView"><strong>ColoredShadowImageView</strong></a></p><p>This is a second library in that compilation which allows to create a beautiful shadow around the image (ImageView) based on corresponding area colors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*moI6-33gNR_3nWIyqLntxQ.png" /></figure><p>The documentation includes a sample apk, setup, usage and some customisations which can be applied to the code. <br>The project is released under Apache 2.0 license.</p><p><strong>23. </strong><a href="https://github.com/akaita/easylauncher-gradle-plugin"><strong>easylauncher-gradle-plugin</strong></a></p><p>This library helps with modifying a launcher icon of each of your app-variants using simple Gradle rules by adding ribbons of any color, overlaying your own images or changing the colors of the icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OThPIyYUvuBWU4pxYHGF1g.png" /></figure><p>The documentation contains a usage of the library, how to customise its behaviours, describes available options and a project structure.<br>It is released under Apache 2.0 license.</p><p><strong>24. </strong><a href="https://github.com/SIMMORSAL/ConcealerNestedScrollView"><strong>ConcealerNestedScrollView</strong></a></p><p>This is a library which simplifies hiding Views from top and bottom when scrolling a custom NestedScrollView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*f07r_dkzopXNBITUHP_PqA.gif" /></figure><p>In the documentation there is a manual how to achieve this effect. There is also no license.</p><p><strong>25. </strong><a href="https://github.com/andremion/Theatre"><strong>Theatre</strong></a></p><p>This is a per project from <a href="https://medium.com/@andremion">André Mion</a> which uses Clean Architecture + MVVM + Reactive Extensions + Android Architecture Components. The main purpose is using the latest practices and libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CqxeYsnc1LlMTOalh_Slog.gif" /></figure><p>The project uses libraries like:</p><p>Android KTX, Android Architecture Components, Dagger 2, RxJava, RxKotlin, RxAndroid, ConstraintLayout, Glide and many more. It’s really worthy to check!<br>License: Apache 2.0.</p><p>If you like my article, please don’t forget to click 👏👏👏 to recommend it to others 👏👏👏.</p><p>Also, to be notified about my new articles and stories, follow me on <a href="https://medium.com/@mmbialas">Medium</a> and <a href="https://twitter.com/mmbialas">Twitter</a>. You can find me on <a href="https://www.linkedin.com/in/mmbialas">LinkedIn</a> as well. Cheers!</p><p><em>Originally published at </em><a href="https://medium.com/@mmbialas/25-new-android-libraries-projects-and-tools-worthy-to-check-in-spring-2018-68e3c5e93568"><em>medium.com</em></a><em> on April 17, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=578f0c32ad25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting rid of boilerplate code with Lombok (Android)]]></title>
            <link>https://medium.com/@shankar.kpu/getting-rid-of-boilerplate-code-with-lombok-android-9bef086b9da1?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bef086b9da1</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 16:53:55 GMT</pubDate>
            <atom:updated>2018-04-27T06:52:40.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*joSFHS9s4ly8c054y7T8tw.png" /></figure><p>As a software developer, you would have created several model classes (POJOs), which require several boilerplate code (constructors, getters, setters, toString(), equals() , hashCode()). These boilerplate code usually makes these model classes lengthy, difficult to read, and for any change in a variable, you’d need to make those changes in each of these methods.</p><p>These can be gotten rid of by using <strong>Lombok.</strong></p><blockquote>Lombok is a java library that automatically plugs into your editor and build tools, to generate those boilerplate code, keeping your code short, clean, hence, spicing up your java.</blockquote><p><em>Also note that Lombok won’t make your android application any ‘heavier’ because lombok is a compile-time only library. Cool right?</em></p><p>Regular model class without lombok</p><pre>import java.util.Date;</pre><pre>public class User {<br> private String userName;<br> private String fullName;<br> private int age;<br> private double height;<br> private Date dateOfBirth;</pre><pre>public User(String userName, String fullName, int age, double height, Date dateOfBirth) {<br> this.userName = userName;<br> this.fullName = fullName;<br> this.age = age;<br> this.height = height;<br> this.dateOfBirth = dateOfBirth;<br> }</pre><pre>public String getUserName() {<br> return userName;<br> }</pre><pre>public void setUserName(String userName) {<br> this.userName = userName;<br> }</pre><pre>public String getFullName() {<br> return fullName;<br> }</pre><pre>public void setFullName(String fullName) {<br> this.fullName = fullName;<br> }</pre><pre>public int getAge() {<br> return age;<br> }</pre><pre>public void setAge(int age) {<br> this.age = age;<br> }</pre><pre>public double getHeight() {<br> return height;<br> }</pre><pre>public void setHeight(double height) {<br> this.height = height;<br> }</pre><pre>public Date getDateOfBirth() {<br> return dateOfBirth;<br> }</pre><pre>public void setDateOfBirth(Date dateOfBirth) {<br> this.dateOfBirth = dateOfBirth;<br> }</pre><pre>@Override<br> public boolean equals(Object o) {<br> if (this == o)<br> return true;<br> if (o == null || getClass() != o.getClass())<br> return false;</pre><pre>User user = (User) o;</pre><pre>if (age != user.age)<br> return false;<br> if (Double.<em>compare</em>(user.height, height) != 0)<br> return false;<br> if (userName != null ? !userName.equals(user.userName) : user.userName != null)<br> return false;<br> if (fullName != null ? !fullName.equals(user.fullName) : user.fullName != null)<br> return false;<br> return dateOfBirth != null ? dateOfBirth.equals(user.dateOfBirth) : user.dateOfBirth == null;</pre><pre>}</pre><pre>@Override<br> public int hashCode() {<br> int result;<br> long temp;<br> result = userName != null ? userName.hashCode() : 0;<br> result = 31 * result + (fullName != null ? fullName.hashCode() : 0);<br> result = 31 * result + age;<br> temp = Double.<em>doubleToLongBits</em>(height);<br> result = 31 * result + (int) (temp ^ (temp &gt;&gt;&gt; 32));<br> result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);<br> return result;<br> }</pre><pre>@Override<br> public String toString() {<br> return &quot;User{&quot; +<br> &quot;userName=&#39;&quot; + userName + &#39;\&#39;&#39; +<br> &quot;, fullName=&#39;&quot; + fullName + &#39;\&#39;&#39; +<br> &quot;, age=&quot; + age +<br> &quot;, height=&quot; + height +<br> &quot;, dateOfBirth=&quot; + dateOfBirth +<br> &#39;}&#39;;<br> }<br>}</pre><p><strong>But with Lombok</strong></p><pre>import java.util.Date;</pre><pre>import lombok.Data;</pre><pre>@Data<br>public class User {<br> private String userName;<br> private String fullName;<br> private int age;<br> private double height;<br> private Date dateOfBirth;<br>}</pre><p>Soooooooooo EASY right?</p><p>1. Download <a href="https://plugins.jetbrains.com/plugin/6317"><strong>Lombok IntelliJ Plugin</strong></a> to enable lombok support in your Android Studio.</p><ul><li>Go to File &gt; Settings &gt; Plugins</li><li>Click on Browse repositories...</li><li>Search for Lombok Plugin</li><li>Click on Install plugin</li><li>Restart Android Studio</li></ul><p><em>Note: This requires gradle v2.12 or newer</em></p><p>2. Add this to your application dependency block</p><pre>dependencies {<br>	compileOnly &#39;org.projectlombok:lombok:1.16.20&#39;<br>	annotationProcessor &#39;org.projectlombok:lombok:1.16.20&#39;<br>}</pre><p>3. Create a file called <strong>lombok.config</strong> in your project’s root directory, and add this in it</p><pre><strong>lombok.addGeneratedAnnotation</strong> = false</pre><p>That’s all!!! No more unnecessary lengthy code :)</p><p><strong>For more information</strong></p><p>Thanks for reading and keep coding smart ;)</p><p><em>Originally published at </em><a href="https://blog.chizobaogbonna.me/getting-rid-of-boilerplate-code-with-lombok-android-95e03a281b34"><em>blog.chizobaogbonna.me</em></a><em> on February 5, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bef086b9da1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple weather forecast app using Kotlin, Retrofit and RxJava2]]></title>
            <link>https://medium.com/@shankar.kpu/simple-weather-forecast-app-using-kotlin-retrofit-and-rxjava2-df8611d1431d?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/df8611d1431d</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Sun, 14 Jan 2018 23:06:35 GMT</pubDate>
            <atom:updated>2018-04-24T11:15:38.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gKuJiVcDSCanHh52E7P1KQ.jpeg" /></figure><p>In the last weekend I decided to dive more into Kotlin and fetching data from web API using RxJava2 and Retrofit. The app will get basic info about current weather and also for weather for next hours and days in a week. In the end of this article I provided the link to the full app source code on Github.</p><p>The tools I decided to use were:</p><ul><li>Kotlin</li><li>Retrofit 2</li><li>RxJava and reactive libraries like RxBinding, ReactiveNetwork, RxAndroid</li><li>Android Architecture Components(Room, ViewModel)</li><li>Dagger2</li><li>Some libraries like MPAndroid chart</li><li>Also Mockito for writing tests</li></ul><p>I decided to use <a href="https://darksky.net/dev/docs"><strong>Dark Sky API</strong></a><strong> </strong>to get weather data.</p><p>Here is how the Retrofit interface looks like:</p><p>So, in the UI the user should get the current weather by providing the city name. In this case we need to map this name to actual latitude and longitude.</p><p>This can be achived by using <a href="https://developer.android.com/reference/android/location/Geocoder.html"><strong>Geocoder</strong></a>, but i decided to use its API directly by Retrofit. This information will be fetched and then pass to our RemoteWeatherService(just for fun ✌️)</p><p>Here is how the interface for fetching location by name will look like:</p><p>The full endpoints for both services can be seen on the API documentations.</p><p>So we have two services, which will fetch <a href="http://reactivex.io/documentation/single.html"><em>Single</em></a>. It is good to have Single instead of <a href="http://reactivex.io/documentation/observable.html"><em>Observable</em></a>, because we need to get only one item and this should be finited action(not like we will be waiting for other events).</p><p>Next, we need to combine the results of those two. As we know, the <em>RemoteWeatherService</em> is depended on <em>RemoteLocationService</em>, we need to know the location first to fetch weather for specific place.</p><p>To perform this action we will use some repository, which will deliver the combined result.</p><p>Here is how we can combine those two Single:</p><p>As we can see wee need to provide dependencies to this repository. This can be achived with Dagger using constructor injection.</p><p>Again, our aim is to combine those to method request to get the one <a href="https://en.wikipedia.org/wiki/Data_transfer_object"><em>DTO(Data-Transfer-Object)</em></a>. So the <em>getWeather</em> method is performing the first call and when we gather its response(in this case this will be the <em>LocationResponse </em>object)it is flatMapped with another call, which will fetch the <em>WeatherReponse </em>object<em>. </em>With combining those two objects we can create the <em>WeatherDetailsDTO </em>object which we can pass to the upper layer of our application. In this case, this will be the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html"><em>ViewModel</em></a>.</p><p><em>WeatherViewModel </em>can have the reference to this <em>WeatherRepository</em>(actually, the <em>WeatherRepository </em>is just an interface, <em>WeatherViewModel </em>really don’t need to know about the actual implentation). So <em>WeatherViewModel </em>can have method like this:</p><p>For this case ViewModel is just an another abstraction, which is useful for testing and clean code. It shares this DTO object to whatever View that subscribes to the <em>getWeather </em>method.</p><p>Now, we can subscribe to this method from our Activty and do whatever we want with this <em>WeatherDetailsDTO </em>object. Let’s take a look on example:</p><p>We can invoke this method in our activity, and fetch the wanted weather info. Of course, we should manage our <a href="http://reactivex.io/RxJava/javadoc/io/reactivex/disposables/Disposable.html"><em>Disposable </em></a>and add it to some <a href="http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/disposables/CompositeDisposable.html"><em>CompositeDisposable</em></a>. We can get the input from some <em>EditText</em>:</p><p>So this was the basic flow of the app. There are others functionality with very similiar flow, but also with the Room database layer instead of the web API. Again, in this case the <em>WeatherRepository </em>can combine the data from Room or web API and then pass it to the ViewModel. ViewModel doesn’t need to know if the data was from Room database or from internet.</p><p>Lastly, let’s take a look on some tests. First here is how the basic <em>getWeather </em>from <em>WeatherRepository </em>can look like:</p><p>We mocked the behaviour of our Retrofit API services, which in this test will return some prepared mock object for <em>LocationResponse </em>and the <em>WeatherResponse. </em>Then we are invoking our method which should return the combined object from those two calls. We also check if there was an interaction with <em>RemoteWeatherService </em>after the <em>LocationWeatherService </em>request has ended successfully with <em>LocationResponse. </em>For this, we can use the <a href="https://static.javadoc.io/org.mockito/mockito-core/2.6.9/org/mockito/ArgumentCaptor.html"><em>ArgumentCaptor</em></a><em> </em>which can be used to get the argument passed as an parameter in between our test.</p><p>In the end, let’s take a look on ViewModel basic test.</p><p>Again, we are using <em>Mockito.verify() </em>method with <em>ArgumentCaptor </em>to check if there is an interaction between ViewModel and WeatherRepository with expected method arguments.</p><p>So thats it. You can see much more in the whole source code of the app which can be found here:</p><p>I hope this can be helpful for you. If you liked this article, don’t forget to 👏 ! It will give me some motivation to make more :)</p><p>Cheers!</p><p><em>Originally published at </em><a href="https://android.jlelse.eu/simple-weather-forecast-app-using-kotlin-retrofit-and-rxjava2-c4b1f4d9344e"><em>android.jlelse.eu</em></a><em> on January 14, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df8611d1431d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The (Complete) Android Splash Screen Guide]]></title>
            <link>https://medium.com/@shankar.kpu/the-complete-android-splash-screen-guide-58735f33f81b?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/58735f33f81b</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Wed, 06 Dec 2017 06:22:02 GMT</pubDate>
            <atom:updated>2018-04-17T11:58:46.989Z</atom:updated>
            <content:encoded><![CDATA[<p>In the past, having splash screens in your Android app were not recommended. It didn’t make much sense to intentionally delay the user by adding a splash screen that shows for x seconds. Am sure no one launches an app just to see a splash screen (more on this later).</p><blockquote>Getting users to the content they care about should be your #1 priority</blockquote><p>Well, when <a href="https://material.io/guidelines/">Material Design</a> dropped with a pattern called <a href="https://material.io/guidelines/patterns/launch-screens.html">Launch Screen</a> (Splash Screen), someone from the Android team shared a <a href="https://plus.google.com/+AndroidDevelopers/posts/Z1Wwainpjhd">post</a> on how to do splash screens the ‘right’ way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*NT3PQWQINfbKFyYVL3oQQg.png" /><figcaption>Branded Splash Screen</figcaption></figure><p>In this post I will walk through 4 common methods of implementing splash screens on the Android platform:</p><ol><li>Using a Launcher Theme (<strong>The good</strong>)</li><li>Using a Launcher Theme with a Dedicated Splash Activity (<strong>The okay</strong>)</li><li>Using Timers (<strong>The bad</strong>)</li><li>Using Smart Timers (<strong>The ugly</strong>)</li></ol><p>When your app is launched and it isn’t in memory yet, there may be some delay between when the user starts your app and when your launcher Activity’s onCreate() is actually called.</p><p>During the ‘cold start’, the window manager tries to draw a placeholder UI using elements from the app theme like the windowBackground. So, rather than showing the default windowBackground (usually white or black), you can change it to a custom drawable that shows your splash screen. This way the splash screen only shows when needed and you don’t slow down your users.</p><p>The key is creating a custom theme that overrides <strong>android:windowBackground</strong>, then replacing that custom theme with your standard theme before calling <em>super.onCreate()</em> in your Activity.</p><p><strong>Implementation</strong></p><p>In this example, I will assume your app main theme is named <strong>AppTheme</strong>, but if it’s not then you can replace all occurrence of <strong>AppTheme </strong>with the name of your app main theme.</p><p>You will have to create a new theme for the launcher. The only element we are interested in overriding in this theme is the windowBackground, so the launcher theme will be:</p><p>To inherit every other attribute in your main theme, the dot notation was used by prefixing the name of the theme (<strong>AppTheme</strong>), separated by a period (<strong>.</strong>).</p><p>Let’s define the launch_screen drawable. While you could just use a simple image, it will end up stretched to fill the entire screen. Instead, you can use an XML file such as:</p><p>Then apply the launcher theme to your launcher Activity in your AndroidManifest.xml file using:</p><pre><strong>android:theme=”@style/AppTheme.Launcher”</strong></pre><p>The easiest way to transition back to your normal theme in your launcher (main) activity is to call setTheme(R.style.AppTheme) before <em>super.onCreate()</em> and <em>setContentView()</em>:</p><p>You can read more about this approach from the source <a href="https://plus.google.com/+AndroidDevelopers/posts/Z1Wwainpjhd">here</a>.</p><p><strong>Pros:</strong></p><ol><li>No launch/splash activity needed — there is no delay such as there would be if you were launching a second activity from a dedicated splash screen activity.</li><li>No artificial delays — No intentional x seconds delay. Only showing the splash screen when the system is loading up the app.</li></ol><p><strong>Cons:</strong></p><p>I have seen 3 very common complains about this approach.</p><ol><li>The <a href="https://android.jlelse.eu/which-splash-screen-approaches-is-better-4de3128988fd#.8jokh29uw">splash screen showing again</a> if the activity was killed and recreated by the system. In most cases, this is not a very serious issue, but you can use <strong>Method 2</strong> to fix it.</li><li>Some developers want to have a dedicated splash screen Activity that routes to different pages based on some state after the splash screen is done. Again you can easily do this using <strong>Method 2</strong> below, but sometimes this dedicated router Activity end up getting really messy.</li><li>Not able to load heavy data/components while the splash screen is shown. It’s usually a bad idea to require heavy data or components to be loaded before the app is actually started (there are some exceptions). You can try one of the suggestions below:</li></ol><p>i) Try to lazy load your components/modules/libraries. Except a component is really really required for the app to work, try not to load it at launch time rather load it when you need it or use a background thread to load it after the app has started. Try to keep your Application onCreate() as light as possible</p><p>ii) Make use of caching. Except that info changes very frequently, you should cache it. So when next the user comes to your app, you can show this cached content while you load more recent content.</p><p>I think we should strive to remove things like long splash screens, ProgressDialogs that make the user unable to perform any other action apart from just staring at the screen. You never know how long it will take to load that data from the Internet.</p><blockquote>If your app connects to the web, assume that anything that can go wrong will go wrong. This way you can build for the millions of people still using unstable 2g and 3g connections.</blockquote><p>This method builds on top <strong>Method 1</strong>. It requires you to have a dedicated splash screen Activity. This allows you to quickly solve the first 2 issues in <strong>Method 1</strong>.</p><p>All you have to do in this step is to create a new splash Activity and assign the launcher theme to it in your AndroidManifest.xml file (Like in <strong>Method 1</strong>). Then edit your splash activity to route to the various pages. Look at the example below:</p><p><strong>Pros:</strong></p><ol><li>Solves the first two issues listed in <strong>Method 1</strong>.</li></ol><p><strong>Cons:</strong></p><ol><li>I have seen this routing thing easily get ugly.</li><li>Small delay transitioning between Activities.</li><li>It’s easy to forget and start doing some long running operations here.</li></ol><p>This is the old easy approach. You just have to create a dedicated splash screen Activity that shows up for x seconds, then opens the appropriate activity. You get more flexibility here as you can add animations, custom views or any other element you can normally fit into an Activity layout. A very basic implementation of this will look like this:</p><p><strong>Pros:</strong></p><ol><li>You get a chance to show your awesome animation or some custom design you have built. This really makes sense for games or apps directed to kids.</li><li>More flexibility on what you can do on the splash screen.</li></ol><p><strong>Cons:</strong></p><ol><li>Double whammy — Your launcher Activity usually doesn’t show up immediately when the app is launched, especially when your app is cold starting. The user waits for the cold start looking at only the windowBackground and then waits for your splash screen again before getting to your app content.</li><li>Your awesome animation or design usually only amaze the user the first few times. After that, most users will find it boring and they want to get to the content. I think <strong>Method 4</strong> provides a fix for this.</li><li>Most times the extra delay is not worth it.</li></ol><p>This builds on <strong>Method 3</strong>. So rather than make the delay fixed, you vary it based on whether the user is launching the app for the first time or not. Here is an example using SharedPreferences:</p><p><strong>Pros:</strong></p><p>Inherits all <strong>Method 3</strong> pros.</p><ol><li>This might fix the issue of the user getting tired of seeing your splash screen showing up for a long period of time.</li></ol><p><strong>Cons:</strong></p><ol><li>Double whammy — The issue in method 3 still exists here</li><li>Most times the extra delay is not worth it.</li><li>I haven’t used this method before, but I think there might be some lag while reading from storage.</li></ol><p>Okay, so that’s it for splash screens on Android. If I missed any other common implementation, please let me know in the comment section below.</p><p><em>Originally published at </em><a href="https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565"><em>android.jlelse.eu</em></a><em> on December 6, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58735f33f81b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture — Kotlin, Dagger 2, RxJava, MVVM and Unit Testing]]></title>
            <link>https://medium.com/@shankar.kpu/clean-architecture-kotlin-dagger-2-rxjava-mvvm-and-unit-testing-329c6f2e863c?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/329c6f2e863c</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Tue, 05 Dec 2017 12:59:41 GMT</pubDate>
            <atom:updated>2018-04-17T12:20:51.090Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will see how we implement a Clean architecture for our Android application using Dagger 2 and MVVM especially. All code samples are taken from the repo below:</p><p>To start the discussion, it might be worth discussing DI. I have used Dagger Android’s libraries to help with DI across the app. Specifically, I am using the DispatchingAndroidInjector&lt;T&gt; where T is a concrete Android class, such as an Activity, Fragment, Service etc. Only recently did I learn this and yet I feel that it’s power is under-estimated. In a previous incarnation of the repo above, I was using scopes and Components to define application-wide and activity-level dependency objects. (Sigh!)</p><p>Let’s look at our Application class to start us off.</p><p>As you can see, we are injecting a DispatchingAndroidInjector&lt;T&gt; where T is the Android Activity. What does this do? From the documentation it: <em>Performs members-injection on instances of core Android types (e.g. Activity, Fragment). </em>However, I like to think of it in this way. Given that an Application has many Activities, the DispatchingAndroidInjector enables objects defined in the AppModule to be visible to Activity-level modules that will be built later.</p><p>The AppModule looks like this:</p><p>As you can see, I have defined a number of application-wide objects such as OkHttpClient, ApiService etc. There is nothing extraordinary of this module. However, it’s corresponding component is quite interesting:</p><p>The AppComponent above binds the Application class to the AppModule. But it does more. It also references the ActivityBuilder which looks like this:</p><p>The ActivityBuilder above binds the MainActivityModule with the MainActivity. Previously, I remember using custom scopes to confine objects to particular modules, or Android Views (Activities, Fragments) — such as confining a Presenter’s instance to it’s associated Activity. However, the Dagger Android libraries now simplify this to such a degree that we no longer need to provide a Component for the MainActivityModule or any other activity level Dagger Module . The MainActivityModule can then provide the MainActivityViewModel while injecting the objects defined in the AppModule, such as our Rx SchedulerProvider, and any objects constructed using constructor injection such as the Repository instance passed as an argument into the provideViewModel() function below:</p><p>Up to this point, we have provided a framework to inject our View Model into the MainActivity. Let’s see the MainActivity code to see how we do this:</p><p>Oh wait! That’s strange. Where’s the Dagger Injection code? All that verbose stuff that we used to write. Where’s it gone? It doesn’t exist anymore. Do you remember the ActivityBuilder defined above — that innocuous abstract class? In there, we bound the MainActivityModule to the MainActivity using a @ContributesAndroidInjector. This provided the link between the module and the Activity. But, how did it inject the MainActivityViewModel in the Activity code above? Well, the MainActivity is a subclass of DaggerActivity which contains one interesting line. Let’s look at the source code of the DaggerActivity:</p><p>The line AndroidInjection.inject(this); will inject any DI objects referenced by that particular activity — which in this case is the MainActivity. That means, therefore, that if you do not wish to extend your Activity with DaggerActivity, you can insert that line in your onCreate() method.</p><p>But a question still remains. How does the annotation, @ContributesAndroidInjector, know it can inject the MainActivityViewModel into the MainActivity? The @ContributesAndroidInjector generates an AndroidInjector&lt;T&gt; where T is a concrete Android class (an Activity, Fragment etc.). The interesting aspect about the AndroidInjector&lt;T&gt; is that it is an interface — its concrete implementation is the DispatchingAndroidInjector&lt;T&gt; that we saw before. There’s a small line in the docs for this class which reveals how this is achieved:</p><blockquote>This class relies on an injected mapping from each concrete class to an <em>AndroidInjector.Factory</em> for an <em>AndroidInjector</em> of that class. Each concrete class must have its own entry in the map, even if it extends another class which is already present in the map</blockquote><p>Now that we have a brief understanding of how we can use Dagger to provide the DI for our app, now we can start talking about MVVM.</p><p>Let’s go back to the MainActivity shown above. We have all our RxJava 2 disposables (or the subscriptions) in the Activity — as held by the CompositeDisposable. What’s the advantage of this? Coming from a background of using MVP, it’s so easy to forget about clearing our Rx subscriptions and disposing of them. In fact, I even remember this causing a bug in one of my apps. Finding the root cause of that bug was extremely difficult because disposing of Rx subscriptions and how they tie into an Activity’s lifecycle is not something we automatically think of when using MVP — we tend to hold the subscriptions (CompositeSubscription or CompositeDisposable) in the Presenter, or a BasePresenter, and this can blind us to the concept that Rx subscriptions should be tied to the lifecycle of the Android view class. In my view, this is one of the most valuable benefits of MVVM over MVP — not from a code point of view, but from a developer’s view of the code — it reminds us of what’s required.</p><p>We can now take a closer look at the ViewModel:</p><p>As you can see, the key responsibilities of the ViewModel is to provide data from a Repository and enforce Rx Scheduling. The ViewModel has no reference to the Activity or Android view which means we reduce the likelihood of memory leaks.</p><p>However, did you notice that the ViewModel does <em>not </em>interact with the ApiService directly — but instead interacts with the Repository class. The Repository class contains a dependency to the ApiService as shown below:</p><p>So why have we inserted an extra layer, the Repository layer, in between the ApiService and the ViewModel? Even though the Repository class in this case simply passes the data from the api to the ViewModel, there could be a requirement to store the data into some form of storage. Now we need some logic to determine whether to retrieve data from the API or from local storage and this is a separate responsibility of concern. Having a clear separation of concerns is a key pillar of maintaining Clean Architecture. The ViewModel’s key responsibility is to expose states for the View to consume to ensure the View receives the latest data. The ViewModel’s concern is <em>not </em>to decide where the data comes from; that’s the concern of the Repository class(es).</p><p>The following diagram summarises what we have learned so far. The arrows representing the direction of the flow of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Ax8N7LHIdXHvwsJgo4S1vQ.png" /><figcaption>Data flows from right to left — there is no feedback or bi-directional flow of data.</figcaption></figure><p>Let’s see how we can now unit test our ViewModel using Mockito.</p><p>One of the biggest issues we faced as a team with the introduction of Kotlin was unit testing. We had unit tests for all our presenters and that was great because last year we felt we had achieved a test coverage that we were pleased with — even though everything wasn’t unit tested, but the fact that all our presenters had unit tests meant that we could be fairly comfortable knowing that our core logic was unit tested. However, the introduction of Kotlin this year changed that — suddenly, we were starting a process of removing unit tests because they all used Mockito and as we know Mockito does not support mocking final classes. Eventually, it got to such a point that we knew something had to change. All the work we achieved in 2016 was being undone by the introduction of Kotlin and that isn’t right.</p><p>So a little more research into Mockito and we found this dependency that allows us mock final classes (without using PowerMockito).</p><pre>testImplementation &#39;org.mockito:mockito-inline:2.11.0&#39;</pre><p>The Inline Mockito dependency allows us to mock final classes and methods. Even though there are a few issues with it, as it’s still being developed, it generally worked very well for us. It means we can write our unit tests in the same way as we have done before. Let’s see the unit test for our MainActivityViewModel:</p><p>Our unit tests look quite familiar — we wouldn’t automatically deduce that we are using the Mockito Inline library rather than the standard Mockito library. This is what makes the inline library powerful. We created a mock of our dependency to the ViewModel — the Repository is mocked using the @Mock annotation. We then setup the Rx schedulers to use the main thread of the background and foreground schedulers. Once that’s done, we can create an instance of the class under test (the MainActivityViewModel).</p><p>As the ViewModel returns Observables, or in this case a Single, we need a means of subscribing to that Single emitted while carrying out our tests. That is where our TestObserver comes in. It allows us to subscribe to the Single&lt;IpAddress&gt; emitted by the ViewModel. We can assert that there were no errors and we can assert that the IpAddress object emitted is the expected outcome. We can unit test our Repository layer code in a similar manner too.</p><p>In conclusion, I hope I have been able to impart some of the caveats in developing a Clean Architecture using Kotlin, Dagger 2, RxJava and the MVVM pattern that is testable. Keep coding!!</p><p><em>Originally published at </em><a href="https://medium.com/@rahul.singh/clean-architecture-kotlin-dagger-2-rxjava-mvvm-and-unit-testing-dc05dcdf3ce6"><em>medium.com</em></a><em> on December 5, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329c6f2e863c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Architecture Components: Room — Introduction]]></title>
            <link>https://medium.com/@shankar.kpu/android-architecture-components-room-introduction-262bfeda0763?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/262bfeda0763</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Mon, 23 Oct 2017 19:15:53 GMT</pubDate>
            <atom:updated>2018-04-17T12:00:32.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ioJNDShaXT2uHHWM5b556w.png" /></figure><p>Recently Google announced a set of new libraries for designing Android application’s architecture — <a href="https://android-developers.googleblog.com/2017/05/android-and-architecture.html">Android Architecture Components</a>. It’s a collection of libraries, due to which you’re able to create consistent, fully testable and maintainable app. Sounds good?</p><p>In Architecture Components packet we get:</p><ul><li><strong>Room</strong> — a database library</li><li><strong>Lifecycle Components </strong>(including LiveData, ViewModel, LifecycleObservers and LifecycleOwners) — a library for handling your app’s lifecycle</li><li><strong>Paging Library</strong> — a small library to help you load data gradually</li></ul><p>Today we’ll focus on <strong>Room</strong> library. Let’s start!</p><p>Room is a database library. From the <a href="https://developer.android.com/topic/libraries/architecture/room.html">documentation</a>:</p><blockquote>Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.</blockquote><p>So basically, Room makes using SQLite much easier for you by implementing annotations, so you don’t have to worry about writing most (but not all!) of the SQLite code and checking it’s correctness.</p><p>Of course, there are a lot of different options to have database in your application. You can either create it by using native solutions (e.g. SQLiteOpenHelper), or use one of the existing library (<a href="http://greenrobot.org/greendao/">greenDAO</a>, <a href="http://ormlite.com/">OrmLite</a>, <a href="https://realm.io/">Realm</a> and much more). However, none of these solutions has all these advantages:</p><ul><li>compile-time verification of SQL queries — each @Query and @Entity is checked at the compile time, so there’s no risk of runtime error that might crash your app (and it doesn’t check only syntax, but also e.g. missing tables)</li><li>very little boilerplate code</li><li>full integration with other Architecture components (like LiveData)</li></ul><p>Ok, let’s assume I convinced you to use Room in your project. How to do it? At first, we need to add Google Maven repository to our build.gradle file:</p><pre>allprojects {<br> repositories {<br> jcenter()<br> google()<br> }<br>}</pre><p>And then we can add proper dependencies to app/build.gradle file:</p><pre>implementation &#39;android.arch.persistence.room:runtime:1.0.0&#39;<br>annotationProcessor &#39;android.arch.persistence.room:compiler:1.0.0&#39;</pre><p>You can check the latest dependencies version in the <a href="https://developer.android.com/topic/libraries/architecture/adding-components.html">Android documentation</a>.</p><blockquote>Note: In this article I use Java. However, if you use Kotlin, you need to replace <em>annotationProcessor</em> with <em>kapt</em> and add <a href="https://kotlinlang.org/docs/reference/kapt.html">kotlin-kapt plugin</a></blockquote><p>No we’re ready to start creating our database. Let’s assume we’d like to get all of the repo for specific user from Github. At first, we need to create our Repo entity:</p><pre><strong>import </strong>android.arch.persistence.room.Entity;<br><strong>import </strong>android.arch.persistence.room.PrimaryKey;<br><strong>import </strong>android.support.annotation.NonNull;</pre><pre>@Entity<br><strong>public class Repo </strong>{<br> @PrimaryKey<br> <strong>public final String </strong>id;<br> <strong>public final String </strong>name;<br> <strong>public final String </strong>url;</pre><pre> <strong>public </strong>Repo(<strong>int </strong>id, <strong>String </strong>name, <strong>String </strong>url) {<br> <strong>this</strong>.id = id;<br> <strong>this</strong>.name = name;<br> <strong>this</strong>.url = url;<br> }<br>}</pre><p>There are actually two requirements for the entity:</p><ul><li><strong>@Entity</strong> annotation on the class</li><li>at least one (*) <strong>@PrimaryKey</strong> field (if it’s non primitive, should be annotated with <strong>@NonNull)</strong></li></ul><p>(*) yeah, you can have more primary keys! Wait for the next article to check why would you need that.</p><p>Then, we need to create DAO for our entity. DAO stands for Data Access Object, so it’s a way of <strong>telling our database how to put the data</strong>:</p><pre><strong>import </strong>android.arch.persistence.room.Dao;<br><strong>import </strong>android.arch.persistence.room.Delete;<br><strong>import </strong>android.arch.persistence.room.Insert;<br><strong>import </strong>android.arch.persistence.room.Query;<br><strong>import </strong>android.arch.persistence.room.Update;<br><strong>import </strong>java.util.List;</pre><pre>@Dao<br><strong>public interface </strong>RepoDao {</pre><pre> @Query(&quot;SELECT * FROM repo&quot;)<br> List&lt;<strong>Repo</strong>&gt; getAllRepos();</pre><pre> @Insert<br> <strong>void </strong>insert(<strong>Repo</strong>... repos);</pre><pre> @Update<br> <strong>void </strong>update(<strong>Repo</strong>... repos);</pre><pre> @Delete<br> <strong>void </strong>delete(<strong>Repo</strong>... repos);<br>}</pre><p>As you can see, we have many different methods here:</p><ul><li><strong>@Insert</strong>, <strong>@Update</strong>, <strong>@Delete</strong> for proper actions: inserting, updating and deleting records</li><li><strong>@Query </strong>for creating queries — we can make select from the database (e.g. get all repos)</li></ul><p>The important thing here is that for @Insert, @Update and@Delete<strong> </strong>you can pass many different types, e.g. for inserting you can have three different methods:</p><pre>@Insert<br><strong>void </strong>insert(<strong>Repo</strong>... repos);</pre><pre>@Insert<br><strong>void </strong>insert(<strong>Repo </strong>repo);</pre><pre>@Insert<br><strong>void </strong>insert(List&lt;<strong>Repo</strong>&gt; repoList);</pre><p>The same applies for the @Query, you can return list of them, or even a good old Cursor!</p><pre>@Query(&quot;SELECT * FROM repo&quot;)<br>List&lt;<strong>Repo</strong>&gt; getAllRepos();</pre><pre>@Query(&quot;SELECT * FROM repo WHERE id=:id&quot;)<br><strong>Repo </strong>getRepo(<strong>int </strong>id);</pre><pre>@Query(&quot;SELECT * FROM repo&quot;)<br>Cursor getRepoCursor();</pre><p>As you saw in the previous example, you can also pass parameter to get repositories by name or limit them:</p><pre>@Query(&quot;SELECT * FROM repo WHERE name=:name&quot;)<br>List&lt;<strong>Repo</strong>&gt; getReposByName(<strong>String </strong>name);</pre><pre>@Query(&quot;SELECT * FROM repo WHERE name=:name LIMIT :max&quot;)<br>List&lt;<strong>Repo</strong>&gt; getReposByName(<strong>int </strong>max, <strong>String</strong>... name);</pre><p>Now it’s time to create our database:</p><pre><strong>import </strong>android.arch.persistence.room.Database;<br><strong>import android.arch.persistence.room.Room</strong>;<br><strong>import </strong>android.arch.persistence.room.RoomDatabase;<br><strong>import </strong>android.content.Context;<br><strong>import </strong>android.support.annotation.NonNull;</pre><pre>@Database(entities = { <strong>Repo</strong>.<strong>class </strong>}, version = 1)<br><strong>public abstract class </strong>RepoDatabase <strong>extends </strong>RoomDatabase {</pre><pre> <strong>private static final String </strong>DB_NAME = &quot;repoDatabase.db&quot;;<br> <strong>private static volatile </strong>RepoDatabase <em>instance</em>;</pre><pre> <strong>static synchronized </strong>RepoDatabase getInstance(Context context) {<br> <strong>if </strong>(<em>instance </em>== <strong>null</strong>) {<br> <em>instance </em>= create(context);<br> }<br> <strong>return </strong><em>instance</em>;<br> }</pre><pre> <strong>private static </strong>RepoDatabase create(<strong>final </strong>Context context) {<br> <strong>return Room</strong>.databaseBuilder(<br> context,<br> RepoDatabase.<strong>class</strong>,<br> DB_NAME).build();<br> }</pre><pre> <strong>public abstract </strong>RepoDao getRepoDao();<br>}</pre><p>What do we have here? At first, we have <strong>@Database</strong> annotation with <strong>entities</strong> to our model classes and <strong>version</strong> of our database (which will be incremented every time we change something in the database schema).</p><p>Then we have getInstance() method which is nothing more than a simple singleton pattern. It’s necessary, because the <a href="https://developer.android.com/topic/libraries/architecture/room.html">documentation</a> says that:</p><blockquote>[…] each <a href="https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.html"><em>RoomDatabase</em></a> instance is fairly expensive, and you rarely need access to multiple instances.</blockquote><p>Next we have static create() method, where we create our database by passing Context, database class, and name.</p><p>The last thing is abstract getRepoDao() method. This is <strong>very important</strong> because database class should have these things at the minimum:</p><ul><li>@Database annotation</li><li>class to be abstract and extend from RoomDatabase class</li><li>class have an abstract method with no parameters and returns the class that is annotated with @Dao (in our case: getRepoDao())</li></ul><p>We’re finally able to make queries and inserts to our database. Let’s see this in practice!</p><p>The important thing here is that all operations must be done in the <strong>background</strong> <strong>thread</strong>. You can do it by using AsyncTask, Handler, RxJava or anything else.</p><p>To add things to the database we need to invoke:</p><pre>RepoDatabase<br> .getInstance(<strong>context</strong>)<br> .getRepoDao()<br> .insert(<strong>new </strong>Repo(1, &quot;Cool Repo Name&quot;, &quot;url&quot;));</pre><p>Getting things is also pretty simple:</p><pre>List&lt;<strong>Repo</strong>&gt; allRepos = RepoDatabase<br> .getInstance(<strong>MainActivity</strong>.<strong>this</strong>)<br> .getRepoDao()<br> .getAllRepos();</pre><p>If you’d like to check Room in practice, but you don’t want to create a whole new project, you can try <a href="https://codelabs.developers.google.com/codelabs/android-persistence/#0">Google Codelabs for Room</a>. There you’ll also find other cool topics, e.g. Type Converters.</p><p>In the next articles I’d write more about modeling relationships, combining Room with Lifecycle Components and RxJava, and much more!</p><p><em>Originally published at </em><a href="https://android.jlelse.eu/android-architecture-components-room-introduction-4774dd72a1ae"><em>android.jlelse.eu</em></a><em> on October 23, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=262bfeda0763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Android development with Kotlin, Part 1]]></title>
            <link>https://medium.com/@shankar.kpu/modern-android-development-with-kotlin-part-1-605b5e820dc7?source=rss-6835330afc53------2</link>
            <guid isPermaLink="false">https://medium.com/p/605b5e820dc7</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Shankar Kuppu]]></dc:creator>
            <pubDate>Thu, 31 Aug 2017 19:44:53 GMT</pubDate>
            <atom:updated>2018-04-17T12:03:56.321Z</atom:updated>
            <content:encoded><![CDATA[<p>It is really hard to find one project that covers all the things that are new in Android Development, so I decided to write one. In this article we will use the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EmpzhfcGQYuVGwNkxxiHnA.png" /><figcaption><a href="https://twitter.com/brijeshmasrani/status/901291501870751745">https://twitter.com/brijeshmasrani/status/901291501870751745</a></figcaption></figure><p><strong>0. Android Studio 3, beta 1<br>1. Kotlin language<br>2. Build Variants <br>3. ConstraintLayout<br>4. Data binding library<br></strong>5. MVVM architecture + repository pattern ( with mappers) + Android Manager Wrappers ( <a href="https://proandroiddev.com/modern-android-development-with-kotlin-september-2017-part-2-17444fcdbe86">Part 2</a> )<br>6. RxJava2 and how it helps us in architecture ( <a href="http://0.0.0.6/%20RxJava2%20and%20how%20it%20helps%20us%20in%20architecture%20Part3">Part 3</a>)<br>7. Dagger 2.11, what is Dependency Injection, why you should use it. (<a href="https://proandroiddev.com/modern-android-development-with-kotlin-part-4-4ac18e9868cb">Part 4</a>)<br>8. Retrofit (with Rx Java2)<br>9. Room (with Rx Java2)</p><p><strong>What our app will be?<br></strong>Our app will be the simplest app that covers all mentioned things: it will have only one feature that fetches all GitHub repositories from user <strong>googlesamples</strong>, saves those data in local database and shows it to user.</p><p>I will try to explain as many lines of code as I can. You can follow looking on commits of code that I published on github.</p><p>Let’s make our hands dirty:</p><p>To install Android Studio 3 beta 1 you have to go to this <a href="https://developer.android.com/studio/preview/index.html">page</a>.</p><p>Note: If you want to install it along with some previous version, on Mac you should rename old version in Application folder to for example “Android Studio Old”. You can find more info, including Windows and Linux <a href="https://developer.android.com/studio/preview/install-preview.html">here</a>.</p><p>Android Studio has support for Kotlin. Go to <strong>Create Android Project</strong>. You will see new thing there: Checkbox with label <strong>include Kotlin support</strong>. It is checked by default. Press <strong>next </strong>twice and select <strong>Empty Activity, </strong>then <strong>finish</strong>.<br>Congrats! You have made first Android app in Kotlin :)</p><p>You can see MainActivity.kt:</p><p>The<strong> .kt </strong>extension means that file is <strong>Kotlin </strong>file.</p><p><strong>MainActivity : AppCompatActivity() </strong>means that we are extending AppCompatActivity.</p><p>Further, all methods have to have a <strong>fun </strong>word and in Kotlin you don’t have to use <strong>;</strong> but you can if you like. You have to use <strong>override </strong>word and not an annotation.</p><p>So, what is the meaning of <strong>?</strong> in <strong>savedInstanceState: Bundle? </strong>? It means that savedInstanceState parameter can be <strong>Bundle</strong> type or <strong>null</strong>. <strong>Kotlin </strong>is null safety language. If you have:</p><pre>var a : String</pre><p>you will get a compilation error, cause <strong>a </strong>must be initialized and it cannot be <strong>null</strong>. That means you have to write:</p><pre>var a : String = &quot;Init value&quot;</pre><p>Also, you will get a compilation error if you do:</p><pre>a = null</pre><p>To make <strong>a </strong>nullable, you have to write:</p><pre>var a : String?</pre><p>Why is this important feature of Kotlin language? It helps us to avoid <a href="https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it">NPE</a>. Android developers are so tired of NPE. Even creator of null, sir Tony Hoare, <a href="https://en.wikipedia.org/wiki/Tony_Hoare">apologized for inventing it</a> . Let’s say that we have nullable <strong>nameTextView</strong>. The following code will give us NPE if it is null:</p><pre>nameTextView.setEnabled(true)</pre><p>But Kotlin, actually, is good and it will not allow us to even do such a thing. It will force us to use ? or !! operator. If we use <strong>?</strong> operator:</p><pre>nameTextView?.setEnabled(true)</pre><p>the line will be proceeded only if <strong>nameTextView</strong> is not a null. In another case, if we use <strong>!! </strong>operator:</p><pre>nameTextView!!.setEnabled(true)</pre><p>it will give us NPE if nameTextView is a null. It is just for adventurers :) .</p><p>This was a little introduction for Kotlin. As we move on, I will stop to describe other Kotlin specific code.</p><p>Often in development, you have different environments. The most usual is <strong>testing</strong> and <strong>production </strong>environment. Those environments can differ in server url, icon, name, target api and so on. At <a href="http://www.fleka.me/">fleka</a>, in every project at the start we have following:</p><ul><li><strong>finalProduction</strong> , that goes to Google Play Store</li><li><strong>demoProduction</strong>, that is version with production server url with new features that are still not on Google Play Store. Our clients can have this version installed next to the one from Google Play so they can test it and give us feedback.</li><li><strong>demoTesting, </strong>same as <strong>demoProduction </strong>with testing server url</li><li><strong>mock, </strong>useful for me as a developer and for designers. Sometimes we have the design ready and our API is still not ready. Waiting for API to be ready to start development is not a solution. This build variant is provided with fake data, so design team can test it and give us feedback. It is really helpful to not procrastinate. Once when API is ready, we are moving our development to <strong>demoTesting</strong> environment.</li></ul><p>In this application, we will have all of them. They will differ in applicationId and name. There is a new api in gradle 3.0.0 <strong>flavorDimension </strong>that allows you to mix different product flavors, so you can mix <strong>demo </strong>and <strong>minApi23 </strong>flavors. In our app, we will use just “default” flavorDimension. Go to build.gradle for App and insert this code inside <strong>android{}</strong></p><p>Go to strings.xml and delete app_name string, so we will not have conflicts. Then press <strong>Sync Now. </strong>If you go to <strong>Build Variants </strong>that are on the left of the screen, you can see 4 different build variants where each of them has two build types: <strong>Debug </strong>and <strong>Release. </strong>Switch to <strong>demoProduction </strong>build variant and run it. Then switch to another one and run it. You should see two applications with different names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8WjjY8JoorqpiStEoEKa5w.png" /></figure><p>If you open activity_main.xml class, you should see that layout is ConstrainLayout. If you ever code iOS application, you know about AutoLayout. ConstraintLayout is really similar to it. They are even using the same Cassowary algorithm.</p><p>Constraints help us to describe what are relations of views. For each view you should have 4 constraints, one for each side. In this case, our view is constrained to parent for each side.</p><p>If you move Hello World text view little bit up in Design tab, in Text tab new line will appear:</p><pre>app:layout_constraintVertical_bias=&quot;0.28&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*KIuQa8AurG-L30M4nscu0g.png" /></figure><p>Design tab and Text tab are synced. Our move in Design tab affects xml in Text tab and vice verse. The Vertical bias describes the vertical tendency of the view to his constraints. If you want view to be centered vertically, you should use:</p><pre>app:layout_constraintVertical_bias=&quot;0.28&quot;</pre><p>Let’s make our activity to show just one repository. It will have name of repository, number of stars, owner and it will show if repository has issues or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fTnFgSc52wAz3LBkLkMQZg.png" /></figure><p>To get such a layout, xml has to look like this:</p><p>Don’t be confused with <strong>tools:text</strong>. It just helps us to have good preview of the layout.</p><p>We can notice that our layout is flat. There are no nested layouts. You should use nested layouts as less as you can cause it can affect performance. More info about it you can find <a href="https://developer.android.com/topic/performance/rendering/optimizing-view-hierarchies.html">here</a>. Also, ConstraintLayout works with different screen sizes really good:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*YET02C_hF4L2W9fsbkgQqg.png" /></figure><p>and I have a feeling that I can achieve wanted result really fast. <br>That was a small introduction in ConstraintLayout. You can find Google code lab <a href="https://codelabs.developers.google.com/codelabs/constraint-layout/index.html?index=..%2F..%2Findex#0">here</a> and there is a documentation about CL on <a href="https://constraintlayout.com/">github</a>.</p><p>When I heard about data binding library, first thing that I asked myself was “Butterknife works really good for me. Plus, I am using a plugin that helps me to get views from xml. Why should I change it?”. Once I learned more about data binding I had the same feeling like I had when I used ButterKnife for the first time.</p><p><strong>What ButterKnife helps us?</strong></p><p>ButterKnife helps us to get rid of boring findViewById. So, if you have 5 views, without Butterknife you have 5 + 5 lines to bind your views. With ButterKnife you have 5 lines. And that’s it.</p><p><strong>What is ButterKnife bad for?</strong></p><p>ButterKnife still does not solve the problem of code maintains. When I used ButterKnife, I often found myself getting a runtime exception, cause I deleted view in xml and I didn’t delete binding code in activity/fragment class. Also, if you want to add view in xml, you have to do binding again. It is really boring. You are losing your time to maintain bindings.</p><p><strong>What about Data Binding library?</strong></p><p>There are a lot of benefits! With Data binding library you can bind your views with just one line of code! Let me show you how it works. Let’s add Data Binding library to our project:</p><pre>// at the top of file <br>apply plugin: &#39;kotlin-kapt&#39;<br></pre><pre>android {<br> //other things that we already used<br> dataBinding.enabled = true<br>}<br>dependencies {<br> //other dependencies that we used<br> kapt &quot;com.android.databinding:compiler:3.0.0-beta1&quot;<br>}</pre><p>Note that version of Data Binding compiler is same as gradle version in your project <strong>build.gradle</strong> file:</p><pre>classpath &#39;com.android.tools.build:gradle:3.0.0-beta1&#39;</pre><p>Press <strong>Sync Now</strong>. Go to <strong>activity_main.xml </strong>class and wrap Constraint Layout with <strong>layout</strong> tag:</p><p>Note that you have to move all of <strong>xmlns </strong>to layout tag. Then press Build icon or use shortcut <strong>Cmd + F9</strong>. We need to build project so Data Binding library can generate class <strong>ActivityMainBinding </strong>that we will use in our MainActivity class.</p><p>If you don’t do Build of the project you will not see <strong>ActivityMainBinding</strong> class cause it is generated at compile time. We still did not finish binding, we just said that we have non-null variable that is <strong>ActivityMainBinding </strong>type. Also, as you can notice I didn’t put <strong>? </strong>on the end of <strong>ActivityMainBinding </strong>and I did not initialize it. How is it possible? <strong>lateinit </strong>modifier allows us to have non-null variables waiting for initialization. Similar to ButterKnife, binding initialization should be done in onCreate method, once when our layout is ready. Further, you should not declare <strong>binding </strong>in onCreate method, cause you will probably use it outside of onCreate method scope. Our <strong>binding </strong>should not be null, so that is why we use <strong>lateinit</strong>. Using <strong>lateinit </strong>modifier we don’t have to null check <strong>binding </strong>variable each time when we access it.</p><p>Let’s initialize our binding variable. You should replace:</p><pre>setContentView(R.layout.activity_main)</pre><p>with:</p><pre>binding = DataBindingUtil.setContentView(this, R.layout.<em>activity_main</em>)</pre><p>That’s it! You successfully bind your views. Now you can access it and apply some changes. For example, let’s change repository name to “Modern Android Medium Article” :</p><pre>binding.repositoryName.<em>text </em>= &quot;Modern Android Medium Article&quot;</pre><p>As you can see we can access to all views (those that have <strong>id</strong>, of course) from <strong>activity_main.xml </strong>through the <strong>binding </strong>variable. That is why <strong>Data Binding </strong>is better than <strong>ButterKnife</strong>.</p><p><strong>Getters and setters in Kotlin</strong></p><p>Probably, you already noticed that we don’t have .setText() method like we do in Java. I would like to stop here to explain how getters and setters work in Kotlin comparing to Java.</p><p>First, you should know why we are using setters and getters. We are using it to hide variables of the class and to allow access only through methods so we can hide details of the class from the clients of the class and forbid same clients to change our class directly. Let’s say that we have Square class in Java:</p><p>Using setA() method we are forbidding clients of the class to set a negative value to <strong>a </strong>cause side of the square must not be negative. Using this approach we have to make <strong>a </strong>private, so it cannot be set directly. That also means the client of our class cannot get the <strong>a </strong>directly , so we have to provide a getter. That getter returns <strong>a</strong>. If you have 10 variables with similar requirements you have to provide 10 getters. Writing such lines is the boring thing where we usually not use our mind.</p><p>Kotling makes our developer’s life easier. If you are calling</p><pre>var side: Int = square.a</pre><p>it does not mean that you are accessing <strong>a </strong>directly. It is same as:</p><pre>int side = square.getA();</pre><p>in Java cause Kotlin autogenerates default getters and setters. In Kotlin, only if you have special setter or getter you should specify it. Otherwise, Kotlin autogenerates it for you:</p><pre><strong>var</strong> a = 1<br> <strong>set</strong>(value) { <strong>field</strong> = Math.abs(value) }</pre><p><strong>field </strong>? What is this now? To make it clear, let’s look at this code:</p><pre><strong>var</strong> a = 1<br> <strong>set</strong>(value) { a = Math.abs(value) }</pre><p>This means that you are calling the <strong>set </strong>method inside the <strong>set </strong>method cause there is no direct access to the property in Kotlin world. This will make infinite recursion. When you call <strong>a = something </strong>it automatically calls <strong>set </strong>method. <br>I hope now it is clear why you must use <strong>field </strong>keyword and how setters and getters work.</p><p>Let’s go back to our code. I would like to present you one more great feature of Kotlin language, <strong>apply </strong>:</p><p><strong>apply </strong>allows you to call multiple methods on one instance.</p><p>We still did not finish with Data Binding, there are more great things. Let’s make ui model class for Repository ( This is UI Model class for Github Repository, holds data that should be displayed, do not misplace it with Repository Pattern). To make Kotlin class you should go to <strong>New -&gt; Kotlin File/Class :</strong></p><pre>class Repository(var repositoryName: String?,var repositoryOwner: String?,var numberOfStars: Int? ,var hasIssues: Boolean = false)</pre><p>In Kotlin, the primary constructor is a part of a class header. If you don’t want to provide the second constructor, that’s it! Your job of class making is finished here. There are no constructor parameters to fields assigns, there are no getters and setters. Whole class in just one line!</p><p>Go back to MainActivity.kt class, and make an instance of Repository class:</p><pre>var repository = Repository(&quot;Medium Android Repository Article&quot;,<br> &quot;Fleka&quot;, 1000, true)</pre><p>As you can notice, there is no <strong>new </strong>keyword for object construction.</p><p>Now let’s go to activity_main.xml and add <strong>data </strong>tag:</p><pre>&lt;data&gt;<br> &lt;variable<br> name=&quot;repository&quot;<br> type=&quot;me.fleka.modernandroidapp.uimodels.Repository&quot;<br> /&gt;<br>&lt;/data&gt;</pre><p>We can access this <strong>repository</strong> variable that is Repository type in our layout. For example we can do following in TextView with <strong>repository_name</strong> id:</p><pre>android:text=&quot;@{repository.repositoryName}&quot;</pre><p><strong>repository_name </strong>text view will show text that is got from repositoryName property of <strong>repository</strong> variable. The only thing that is left is to bind <strong>repository variable </strong>from xml to <strong>repository </strong>from MainActivity.kt.<br>Press <strong>Build </strong>to make Data Binding library to generate needed classes and go back to Main Activity and add this two lines:</p><pre>binding.<em>repository </em>= repository<br>binding.executePendingBindings()</pre><p>If you run the app, you will see that textview will show “Medium Android Repository Article”. Nice feature, huh? :)</p><p>But what if we do following:</p><pre>Handler().postDelayed(<strong>{</strong>repository.repositoryName=&quot;New Name&quot;<strong>}</strong>, 2000)</pre><p>Will the new text be shown after 2000 millis ? No, it will not. You have to set repository again. Something like this will work:</p><pre>Handler().postDelayed(<strong>{</strong>repository.repositoryName=&quot;New Name&quot;<br> binding.<em>repository </em>= repository<br> binding.executePendingBindings()<strong>}</strong>, 2000)</pre><p>But, it will be boring if have to do this every time when we change some property. There is a better solution called <strong>Property Observer.</strong> <br>Let’s first describe what is <strong>Observer </strong>pattern cause we will need it in rxJava section too:</p><p>Probably, you have already heard for <a href="http://androidweekly.net/">http://androidweekly.net/</a> . It is a weekly newsletter about Android Development. If you want to receive it , you have to subscribe onto it giving your email address. After some time, if you decide it, you can stop it going to unsubscribe option on their site.</p><p>This is one example of Observer/Observable pattern. In this case Android Weekly is <strong>Observable</strong>, it emits newsletters each week. Readers are <strong>Observers </strong>cause they subscribe on it, waits for new emits and once when they receive it, they read it and if some of them decide that she does not like it, she/he can stop listening to it.</p><p><strong>Property Observer </strong>in our case is xml layout, that will listen for changes in Repository instance. So, Repository is <strong>Observable.</strong> For example, once when repository name property is changed in the instance of Repository class, xml should be updated without calling:</p><pre>binding.<em>repository </em>= repository<br>binding.executePendingBindings()</pre><p>How to make it using Data Binding library? Data Binding library provide us with BaseObservable class that Repository class should implement:</p><p><strong>BR </strong>is a class that is auto generated once when <strong>Bindable </strong>annotation is used. As you can see, once when the new value is set we are notifying it. Now you can run the app and you will see that repository name will be changed after 2 seconds without calling <strong>executePendingBindings() </strong>again.</p><p>That was all for this part. In next part, I will write about MVVM pattern and Repository pattern and I will write about Android Wrapper Managers. You can find all code <a href="https://github.com/mladenrakonjac/ModernAndroidApp">here</a>. This article cover code up to the following <a href="https://github.com/mladenrakonjac/ModernAndroidApp/commit/0add63eb710a71f44b294e2af5d289c47a89a39a">commit</a>.</p><p>You can find Part 2 here:</p><p>Thanks for reading and follow me for more articles like this. :)</p><p>P.S. Thanks to:</p><ul><li><a href="http://www.kotlinweekly.net/">Kotlin Weekly</a> for publishing this article in Issue #57</li><li><a href="http://androidweekly.net/issues/issue-257">Android Weekly</a> for publishing this article in Issue #274</li></ul><p><em>Originally published at </em><a href="https://proandroiddev.com/modern-android-development-with-kotlin-september-2017-part-1-f976483f7bd6"><em>proandroiddev.com</em></a><em> on August 31, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=605b5e820dc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>