<?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 Myroslav Kolodii on Medium]]></title>
        <description><![CDATA[Stories by Myroslav Kolodii on Medium]]></description>
        <link>https://medium.com/@mkolodii?source=rss-8c1f1fc5e868------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FyanjqT4fwijycOv.</url>
            <title>Stories by Myroslav Kolodii on Medium</title>
            <link>https://medium.com/@mkolodii?source=rss-8c1f1fc5e868------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:11:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mkolodii/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 to find Methods in Android App annotated with Specific Annotation]]></title>
            <link>https://medium.com/@mkolodii/how-to-find-methods-in-android-app-annotated-with-specific-annotation-bf4272e0682d?source=rss-8c1f1fc5e868------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf4272e0682d</guid>
            <category><![CDATA[preview]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[snapshot]]></category>
            <category><![CDATA[classgraph]]></category>
            <dc:creator><![CDATA[Myroslav Kolodii]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 15:20:34 GMT</pubDate>
            <atom:updated>2023-12-20T15:20:34.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Note that it’s not a full guide about how to scan app codebase, but rather particular example, where I show how to use <a href="https://github.com/classgraph/classgraph">ClassGraph</a> library to find all Compose Preview functions. Having those functions, I can create snapshot tests from them automatically, thus getting free snapshot tests with each creation of new Compose Preview function.</p><p>ClassGraph allows to search for classes, methods, annotations etc. Here is example of function that gives us scan results:</p><pre>private fun getScanResult(<br>  // List of package names where scan should be performed.<br>  // Or just provide base app&#39;s package to scan whole codebase<br>  // (i.e. &quot;com.example.myapp&quot;)<br>  packageNames: Array&lt;String&gt;, <br>  // Define, whether or not we want to have private methods in result<br>  includePrivateMethods: Boolean<br>): ScanResult {<br>    return ClassGraph()<br>        .acceptPackages(*packageNames)<br>        // Since we want to search for annotated methods, need to <br>        // include all info - class, method and annotation<br>        .enableClassInfo()<br>        .enableMethodInfo()<br>        .enableAnnotationInfo()<br>        .apply { if (includePrivateMethods) ignoreMethodVisibility() }<br>        .scan()<br>}</pre><p>Now we need to filter result to get only what we need:</p><pre>fun getMethodsWithAnnotations(<br>    annotationClasses: List&lt;Class&lt;out Annotation&gt;&gt;,<br>    packageNames: Array&lt;String&gt;,<br>    includePrivate: Boolean,<br>): List&lt;Method&gt; = buildList {<br>    val scanResult = getScanResult(packageNames, includePrivate)<br><br>    annotationClasses.forEach { annotationClass -&gt;<br>        scanResult.getClassesWithMethodAnnotation(annotationClass)<br>          .forEach { classInfo -&gt;<br>            classInfo.declaredMethodInfo<br>                // Custom method, described further in the article<br>                .filterHavingAnnotation(annotationClass)<br>                .forEach { methodInfo -&gt;<br>                    val method = methodInfo.loadClassAndGetMethod()<br>                    // If method is private, need to make it accessible <br>                    // to be able to invoke it later<br>                    if (Modifier.isPrivate(method.modifiers)) <br>                      method.isAccessible = true<br>                    this@buildList.add(method)<br>                }<br>        }<br>    }<br><br>    scanResult.close()<br>}</pre><p>Now we need to filter result to get methods, annotated with specific annotation. This part is a bit tricky — scan result includes not only methods, that are directly annotated by some annotation, but also those, where direct annotation class is annotated with annotation we need.</p><p>Here is example (see code below) — assume we search for methods, annotated with AnnotationOne. We expect to have functionOne in scan result, but we also get functionTwo — this is because functionTwo is annotated with annotation, which by itself is annotated with AnnotationOne.</p><pre>annotation class AnnotationOne<br><br>@AnnotationOne<br>annotation class AnnotationTwo<br><br>@AnnotationOne<br>fun functionOne() { ... }<br><br>@AnnotationTwo<br>fun functionTwo() { ... }</pre><p>I’ve created two extension methods to have proper filtering:</p><pre>private fun MethodInfoList.filterHavingAnnotation(<br>  annotationClass: Class&lt;out Annotation&gt;<br>): MethodInfoList {<br>    return filter { methodInfo -&gt;<br>        // We need methods directly annotated by &#39;annotationClass&#39;<br>        methodInfo.hasAnnotation(annotationClass) &amp;&amp; <br>          !methodInfo.hasAnnotationClassAnnotatedWith(annotationClass)<br>    }<br>}<br><br>private fun MethodInfo.hasAnnotationClassAnnotatedWith(<br>  annotationClass: Class&lt;out Annotation&gt;<br>): Boolean {<br>    return this.annotationInfo.any { annotationInfo -&gt;<br>        annotationInfo.classInfo.annotationInfo.directOnly()<br>          .any { annotationClassAnnotationInfo -&gt;<br>            annotationClassAnnotationInfo.name == annotationClass.name<br>          }<br>    }<br>}</pre><p>Full code is available <a href="https://github.com/mirokolodii/AndroidComposePlayground/blob/main/app/src/test/java/com/unagit/composeplayground/compose/ReflectionUtils.kt">here</a>.</p><p>In my next article I will show, how to use scan result to create snapshot tests from Compose Preview methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf4272e0682d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-generation of screenshot tests from Compose Previews]]></title>
            <link>https://medium.com/@mkolodii/auto-generation-of-screenshot-tests-from-compose-previews-cdd8711984b7?source=rss-8c1f1fc5e868------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd8711984b7</guid>
            <dc:creator><![CDATA[Myroslav Kolodii]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 11:07:28 GMT</pubDate>
            <atom:updated>2023-12-12T11:07:28.766Z</atom:updated>
            <content:encoded><![CDATA[<h2>How to generate snapshot tests from Compose previews — part 1</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngrZRSTp_hErrsO-CQSvKg.png" /></figure><p>If you ever worked on creation of Android automated UI tests, you probably agree that it’s not an easy task. Launching particular Activity or Fragment requires good app architecture ideally with dependency injection, so that all components, not needed for the test, can be easily mocked.</p><p>Also, in my opinion, creation of good UI test requires a lot of thinking about what exactly should it test, remembering that its creation and maintenance cost is high.</p><p>Here are some scenarios I believe are good candidates for automated UI tests:</p><ul><li><strong>navigation logic</strong>. Assuming there is some conditional navigation from one screen to others, it would be useful to have automated test for that — prepare test data for different navigation scenarios once, which gives clear benefit over manual testing, where one would need to prepare test scenario for each navigation case.</li><li><strong>view with complex view states</strong>. Visibility and position of different UI components are changing depending on view state data. Again, as in previous point, with manual testing it would take much time to prepare test data for each test case and perform each test. With test library like Espresso it’s easy to create automated tests for this.</li></ul><p>On the other side, in many cases you just need to see UI by yourself to judge, whether or not it’s displayed correctly. Or, you can use screenshot (or snapshot) auto tests for this.</p><p>Screenshot tests can be integrated into existing UI tests, so that screenshots are made and compared to base (golden) image during test execution.</p><ul><li><strong>Advantage </strong>of this approach is that screenshot is made from the app running on device or emulator, so app’s logic is involved to render UI.</li><li><strong>Disadvantage </strong>is that you still need to create those UI tests, which may include navigation between states, pressing buttons, mocking objects etc.</li></ul><p>Another approach is to generate screenshots from XML layouts, something what <a href="https://github.com/cashapp/paparazzi">Paparazzi library</a> is doing.</p><ul><li><strong>Advantage</strong>— tests are run as unit tests, so easier to create and faster to execute.</li><li><strong>Disadvantage — </strong>screenshots are generated from ‘raw’ layouts, so app’s view logic is not involved in generation.</li></ul><p>In world of Compose things look much better — whole code inside Compose function is used to generate UI, either with Compose previews or using Paparazzi, which also supports Compose. So, we get UI that looks exactly like in real device, while it’s still run on JVM (so no need for an emulator or a device to run it).</p><p>Now, if you think about it, Compose Preview functions and Compose Paparazzi tests are doing the same thing, but only for different purposes — first one creates preview for visual representation, another one creates snapshot automated test. Wouldn’t it be great though to have these two combined? So we create good Compose preview (with all the different view states, day/night mode etc.) and then it’s also used in screenshot tests automatically, so that we don’t have to create them ourselves.</p><p>Way to achieve this is following:</p><ol><li>Analyze whole application’s codebase and find all Compose Preview functions (i.e. annotated with Preview annotation)</li><li>Invoke those functions one by one, using Paparazzi tests</li></ol><p>Once this is done, usage is very simple — you generate and execute Paparazzi tests in normal way. The only difference is that you don’t have to create those tests— each new Compose Preview function becomes part of automated tests automatically.</p><pre>// Generate golden images<br>./gradlew recordPaparazziDebug<br><br>// Generate and compare snapshots against corresponding golden images<br>./gradlew verifyPaparazziDebug</pre><p>Part 2 explains, how to implement code analysis to search for annotated functions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd8711984b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use OpenAI API for code reviews]]></title>
            <link>https://medium.com/@mkolodii/how-to-use-openai-api-for-code-reviews-62ffde514ef4?source=rss-8c1f1fc5e868------2</link>
            <guid isPermaLink="false">https://medium.com/p/62ffde514ef4</guid>
            <dc:creator><![CDATA[Myroslav Kolodii]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 17:55:51 GMT</pubDate>
            <atom:updated>2023-12-12T17:53:08.902Z</atom:updated>
            <content:encoded><![CDATA[<p>Inspired by <a href="https://medium.com/@samho1996/how-do-i-make-use-of-chatgpt-to-review-my-code-33efd8f42178">this article</a>, written by Sam Ho, I decided to create similar solution. Even though mentioned article was only eight months old, OpenAI API usage was outdated (probably because of very rapid growth of OpenAI), as well as had to deal with some other issues, so decided to share my experience with rest of community in case it will be helpful for someone else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VZoWIWyC_GEdmCeq" /><figcaption>Photo by <a href="https://unsplash.com/@santesson89?utm_source=medium&amp;utm_medium=referral">Andrea De Santis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Big part of the whole solution is configuration and installation of all needed tools. Our job is to create Node.js application, which will use OpenAI API to make code reviews. I’ve never worked with Node.js applications before, so it was pretty cool experience by itself. I wanted this application to be stand-alone, not part of any other application, so that it can work with any file in any Git repository, directory etc.</p><p>Note: all code examples in this articles are provided for MacOS.</p><p>Create folder for new application, i.e.:</p><pre>$ mkdir openai_review_app<br>$ cd openai_review_app</pre><p><strong>NPM</strong></p><p>We need to have npm installed, which will run Nodejs script for us:</p><pre># Check version of installed npm<br>$ npm -v<br>10.2.4<br># Or install it with Homebrew<br>$ brew install npm<br><br># Init new Node.js app.<br># This command will generate &#39;package.json&#39; for us<br>$ npm init</pre><p><strong>OpenAI</strong></p><p>Installing OpenAI package is straight forward. I had some issues with running it though, so also had to install python. <a href="https://kevingoedecke.com/2023/04/14/how-to-install-openai-cli-on-macos/">This article</a> helped.</p><pre>$ npm install openai<br>$ openai -V<br># All is good if response is similar to<br>openai 1.3.7<br># If instead you get something like below, try to install python as well<br>zsh: command not found: openai<br><br><br># Check that python is installed<br>$ python3 --version<br>Python 3.11.6<br><br># Otherwise<br>$ brew install python3<br></pre><p><strong>Other packages</strong></p><p>We also need to install few other packages, which will help us to create our application:</p><ul><li>fs — gives access to local files in Node.js app</li><li>dotenv — provides configuration file for our app. We will store OpenAI token there.</li></ul><pre>$ npm install fs<br>$ npm install dotenv</pre><p>If you check your app’s directory now, you should see previously generated package.json file, as well as node_modules sub-directory with all the installed packages:</p><pre>$ ls<br>node_modules  package-lock.json package.json<br><br>$ ls node_modules<br>@types   dotenv   mime-types<br>abort-controller event-target-shim ms<br>agentkeepalive  form-data  node-domexception<br>asynckit  form-data-encoder node-fetch<br>base-64   formdata-node  openai<br>charenc   fs   tr46<br>combined-stream  humanize-ms  undici-types<br>crypt   is-buffer  web-streams-polyfill<br>delayed-stream  md5   webidl-conversions<br>digest-fetch  mime-db   whatwg-url</pre><p><strong>OpenAI token</strong></p><p>We need API token (or key) to be able to make OpenAI API calls. Go to <a href="https://platform.openai.com/api-keys">OpenAI API keys page</a> to generate new key. Unfortunatelly, currently free OpenAI account is not usable with its API — after running just few API calls I got You exceeded your current quota … response. The only solution now is to upgrade to Plus account.</p><p>Once you have API token, create .env file in app’s directory and put token there, so that we are able to access it in the app.</p><pre>$ touch .env<br>$ echo &#39;OPEN_API_KEY=&lt;your token&gt;&#39; &gt;&gt; .env<br>$ cat .env<br>OPEN_API_KEY=&lt;your token&gt;</pre><p>Now we should have everything we need to create Node.js script.</p><p>Create new js file, i.e openAI.js:</p><pre>import OpenAI from &quot;openai&quot;;<br>import fs from &quot;fs&quot;;<br>import &#39;dotenv/config&#39;;<br><br>// Set color codes<br>const reset = &#39;\x1b[0m&#39;;<br>const green = &#39;\x1b[32m&#39;;<br>const cyan = &quot;\x1b[36m&quot;<br><br>const openai = new OpenAI(<br>    // API key from &#39;.env&#39; file<br>    { apiKey: process.env.OPENAI_API_KEY }<br>);<br><br>// Get the file path from the command line<br>const filePath = process.argv[2];<br>if (!filePath) {<br>    console.error(&#39;Please provide a file path.&#39;);<br>    process.exit(1);<br>}<br>// Verify script is able to access file<br>fs.accessSync(filePath);<br><br>try {<br>    // Read file content<br>    const content = fs.readFileSync(filePath, &#39;utf8&#39;);<br>    console.log(`${green}File ${filePath}:`);<br>    // Make API call and wait for response<br>    const response = await makeAPIRequest(content);<br>    console.log(`${cyan}${response}`)<br>} catch (err) {<br>    console.error(err);<br>}<br><br>async function makeAPIRequest(content) {<br>    const completion = await openai.chat.completions.create({<br>        /**<br>        * You can adjust content messages, depending on your needs and desired result. <br>        */<br>        messages: [<br>            { &quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are Android software development expert.&quot; },<br>            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Review the code below and provide feedback on how to improve it.&quot; },<br>            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Print original code (but without imports) and add improvement suggestions as comments to original code.&quot; },<br>            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: content }<br>        ],<br>        // For free OpenAI accounts, currently on &#39;gpt-3.5-turbo&#39; is available. <br>        // Plus accounts can use either 3.5 or 4 model.<br>        model: &quot;gpt-4&quot;,<br>    });<br><br>    return completion.choices[0].message.content;<br>}</pre><p>Adjust API request messages according to your needs and expected results. After several tries, I came up with messages (as in below example) that works good for Android/Kotlin related code — I want response to be brief and to include code modification suggestions as comments to original code:</p><pre>messages: [<br>            { &quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are Android software development expert.&quot; },<br>            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Review the code below and provide feedback on how to improve it.&quot; },<br>            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Print original code (but without imports) and add improvement suggestions as comments to original code.&quot; },<br>            { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: content }<br>        ],</pre><p>Next, update package.json and add app’s details.</p><pre>{<br>  &quot;name&quot;: &quot;node_review_app&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;Use OpenAI for code reviews&quot;,<br>  &quot;main&quot;: &quot;openAI.js&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;review&quot;: &quot;node --no-deprecation openai.js&quot;<br>  },<br>  &quot;author&quot;: &quot;Myroslav Kolodii&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;dotenv&quot;: &quot;^16.3.1&quot;,<br>    &quot;fs&quot;: &quot;^0.0.1-security&quot;,<br>    &quot;openai&quot;: &quot;^4.20.1&quot;<br>  }<br>}</pre><p>Note scripts object. Now it’s possible to run application with following command:</p><pre>$ npm review &lt;file_to_review&gt;</pre><p><strong>OpenAI.js</strong></p><p>Here is simple class, written in Kotlin, which we want to get review for.</p><pre>class Test {<br>    var value = 1<br><br>    fun getValue(): Int {<br>        return value<br>    }<br><br>    fun strangefunction() {<br>        for (val i = 4; i &lt; 3; i++) {<br>            // do something<br>        }<br>    }<br>}</pre><p>With help of --prefix we can specify path to our Node.js application, in case it’s in different folder.</p><pre>npm run --prefix NodejsProjects/node_review_app review ~/Test.kt</pre><p>API response:</p><pre>class Test {<br>    var value = 1<br><br>    // Improvement:<br>    // Instead of creating a method to access a class property,<br>    // Utilize the inherent kotlin getter and setter methods. <br>    fun getValue(): Int {<br>        return value<br>    }<br><br>    fun strangefunction() {<br>        // Improvement:<br>        // This loop will never execute because 4 is not less than 3.<br>        // Either the initial or final value should be adjusted so that the loop runs correctly.<br>        for (val i = 4; i &lt; 3; i++) {<br>            // do something<br>        }<br>    }<br>}</pre><p><strong>[Optional] Git hook</strong></p><p>Git hooks are scripts that run automatically on specific Git repo events. Below is an example of Git pre-commit hook, which will run our ‘review’ application on commited files.</p><p>Assuming you are in some Git repo root directory, navigate to .git/hooks and create pre-commit file. In my example, I want only .kt, .java or .xml files to be reviewed.</p><pre>#!/bin/sh<br><br># ------<br># Review commited files with OpenAI<br># Get full path of the staged .kt, .java, .xml files<br>files=$(git diff --cached --name-only --diff-filter=ACM --line-prefix=`git rev-parse --show-toplevel`/ \<br>| grep -E &#39;\.(kt|java|xml)$&#39;)<br><br># Call code review script for each staged file<br>for file in $files<br>do<br>  echo &quot;Reviewing $file&quot;<br>  npm run --prefix /&lt;path_to_Node.js_review_app&gt;/node_review_app review $file<br>done</pre><p><strong>Update</strong></p><p>It takes quite some time (dozen of seconds) to get full response from OpenAI API, so instead I found better solution is to use stream, which works the same way as in ChatGPT — response is returned in chunks while it’s generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ac8EQ6ujy8-LO_RHnrYNyw.gif" /></figure><p>Here is what should be changed in OpenAI.js:</p><pre>async function makeAPIRequest(content) {<br>    const completion = await openai.chat.completions.create({<br>        messages: [<br>            /* Same as previously */<br>        ],<br>        model: &quot;gpt-4&quot;, // or &quot;gpt-3.5-turbo&quot;<br>        stream: true, // here we enable streaming<br>    });<br>    return completion;<br>}<br><br>// And now we can print stream from response into console<br>const response = await makeAPIRequest(content);<br>for await (const chunk of response) {<br>    process.stdout.write(chunk.choices[0]?.delta?.content || &quot;&quot;);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62ffde514ef4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose SearchView]]></title>
            <link>https://medium.com/@mkolodii/compose-searchview-0a38f3843324?source=rss-8c1f1fc5e868------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a38f3843324</guid>
            <dc:creator><![CDATA[Myroslav Kolodii]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 14:41:53 GMT</pubDate>
            <atom:updated>2023-12-09T14:41:53.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yeGvO9Mq4xB1hMvJ" /><figcaption>Photo by <a href="https://unsplash.com/@saeedanathema?utm_source=medium&amp;utm_medium=referral">saeed mhmdi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are very nice <a href="https://github.com/material-components/material-components-android/blob/master/docs/components/Search.md#search-bar-1">SearchBar</a> and <a href="https://github.com/material-components/material-components-android/blob/master/docs/components/Search.md#search-view">SearchView</a> Material components available as Android Views. These are not available in Compose though (at least at the time of writing this article). Let’s feel this gap and create Compose SearchView, which will look similar to Material SearchView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*aUYrUuQkcRDhH2S1vYEMzg.gif" /></figure><p>First we create SearchBox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*pZkjDo_UsDxeg1blQCNfMA.gif" /></figure><p>Code is mostly self-explanatory. The only tricky part is to show hint in text field. I used BasicTextField, because it doesn’t have custom style. Alternatively, TextField can be used — it supports hints out of the box, although has Material Design style, which may not fit app’s design.</p><pre>@Composable<br>fun SearchBox(<br>    onBackClick: () -&gt; Unit,<br>    onSearchTextChanged: (String) -&gt; Unit,<br>) {<br>    var searchText: String by remember { mutableStateOf(&quot;&quot;) }<br><br>    Row(<br>        modifier = Modifier.padding(horizontal = 8.dp, vertical = 16.dp),<br>        verticalAlignment = Alignment.CenterVertically,<br>        horizontalArrangement = Arrangement.spacedBy(8.dp)<br>    ) {<br><br>        // Back icon<br>        Icon(<br>            modifier = Modifier.clickable { onBackClick() },<br>            imageVector = Icons.Default.ArrowBack,<br>            contentDescription = &quot;&quot;,<br>            tint = colorResource(id = R.color.onSurface)<br>        )<br><br>        BasicTextField(<br>            // Show hint, when &#39;searchText&#39; is empty<br>            decorationBox = { innerTextField -&gt;<br>                if (searchText.isBlank()) {<br>                    Text(<br>                        text = stringResource(id = R.string.search_placeholder),<br>                        style = TextStyle(<br>                            color = colorResource(id = R.color.onSurface)<br>                        )<br>                    )<br>                }<br>                innerTextField()<br>            },<br>            modifier = Modifier.weight(1f),<br>            value = searchText,<br>            singleLine = true,<br>            onValueChange = { value -&gt;<br>                searchText = value<br>                onSearchTextChanged(value)<br>            },<br>        )<br><br>        // This is optional animated visibility change<br>        AnimatedVisibility(visible = searchText.isNotBlank()) {<br>            // Clear text icon<br>            Icon(<br>                modifier = Modifier.clickable {<br>                    searchText = &quot;&quot;<br>                    onSearchTextChanged(&quot;&quot;)<br>                },<br>                imageVector = Icons.Default.Clear,<br>                contentDescription = &quot;&quot;,<br>                tint = colorResource(id = R.color.onSurface),<br>            )<br>        }<br>    }<br>}</pre><p>Second goes view with search results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*hYTR7m-p_okY-FTYGSRxSQ.png" /></figure><p>Very simple view with only Text and Divider.</p><pre>fun interface ListItem {<br>    fun getName(): String<br>}<br><br>@Composable<br>fun SearchListView(<br>    items: List&lt;ListItem&gt;,<br>    onItemClick: (ListItem) -&gt; Unit,<br>) {<br><br>    LazyColumn {<br>        itemsIndexed(items) { index, item -&gt;<br>            Text(<br>                modifier = Modifier<br>                    .padding(8.dp)<br>                    .fillMaxWidth()<br>                    .clickable { onItemClick(item) },<br>                text = item.getName()<br>            )<br><br>            // Show divider<br>            if (index != items.size - 1) {<br>                Divider()<br>            }<br>        }<br>    }<br>}</pre><p>Now we use our previously created views in SearchView and add some logic to filter items, based on search text.</p><pre>@Composable<br>fun SearchView(<br>    modifier: Modifier,<br>    items: List&lt;ListItem&gt;,<br>    onItemClick: (ListItem) -&gt; Unit,<br>    onBackClick: () -&gt; Unit,<br>) {<br>    var filteredItems: List&lt;ListItem&gt; by remember { mutableStateOf(items) }<br><br>    Column(modifier = modifier.fillMaxWidth()) {<br><br>        SearchBox(<br>            onBackClick = onBackClick,<br>            onSearchTextChanged = { searchText -&gt;<br>                filteredItems = items.filter { item -&gt;<br>                    item.getName().contains(searchText, ignoreCase = true)<br>                }<br>            }<br>        )<br><br>        Divider(color = Color.DarkGray)<br><br>        SearchListView(<br>            modifier = Modifier.padding(16.dp),<br>            items = filteredItems,<br>            onItemClick = onItemClick,<br>        )<br>    }<br>}</pre><p>That’s it — we have our Compose search view. To be able to display it fullscreen on some search button click, it can be wrapped in <a href="https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#ModalBottomSheet(kotlin.Function0,androidx.compose.ui.Modifier,androidx.compose.material3.SheetState,androidx.compose.ui.unit.Dp,androidx.compose.ui.graphics.Shape,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.ui.unit.Dp,androidx.compose.ui.graphics.Color,kotlin.Function0,androidx.compose.foundation.layout.WindowInsets,androidx.compose.material3.ModalBottomSheetProperties,kotlin.Function1)">ModalBottomSheet</a>.</p><p>Full code is available in this <a href="https://github.com/mirokolodii/AndroidComposePlayground/tree/main/preview/src/main/java/com/unagit/composeplayground/compose_searchview">GitHub repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a38f3843324" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compose previews in Android views]]></title>
            <link>https://medium.com/@mkolodii/compose-previews-in-android-views-b514e6e928d6?source=rss-8c1f1fc5e868------2</link>
            <guid isPermaLink="false">https://medium.com/p/b514e6e928d6</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-compose]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Myroslav Kolodii]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 05:06:13 GMT</pubDate>
            <atom:updated>2023-11-22T05:06:51.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FEB4mE0W4rkItGDH" /><figcaption>Photo by <a href="https://unsplash.com/@joshhild?utm_source=medium&amp;utm_medium=referral">Josh Hild</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Without any doubt, Compose previews is a great feature, which allows to see UI element, created from Composable function, right in Android Studio, without a need to run code in emulator or a device. And this UI will look exactly the same as in real device, which allows to verify the component much faster and in different states by providing different data sets.</p><p>Let’s say we have application with codebase, where both Android views and Compose functions are used. It would be great to have previews for all UI elements, but how to achieve this? One way is to rewrite all Android views into Compose functions and then add previews to them. This approach may be good for a long-term strategy, but re-writing UI of the whole application is not an easy task — it probably doesn’t make much sense to do it on one go, if you compare business value of this change to a time, spent on it.</p><p>Wouldn’t it be great though, if we can use Compose previews for Android views? It is actually possible, with help of <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidView(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)">AndroidView</a>.</p><p>Let’s look at some code, so that we can understand the problem better. Here is example of custom Android view (extending ConstraintLayout), which displays some order status, depending on parameters, provided to init(:Status, :Map&lt;String, String&gt;) function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f979d0a32d1c31e4a54ed5dd88d082/href">https://medium.com/media/e2f979d0a32d1c31e4a54ed5dd88d082/href</a></iframe><p>Above example has simple logic, although, looking at the code, it’s basically impossible to understand, how this view looks like as UI element. Luckily, we have xml layout with preview, right?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8afb5606dade8dde81db7b72be21fce/href">https://medium.com/media/c8afb5606dade8dde81db7b72be21fce/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*9493qIFdiE8lKPN14KPf0A.png" /><figcaption>XML layout preview</figcaption></figure><p>Well… we can get general understanding about its UI, but you still need to run it in the app to understand, how it looks like exactly, specially in different states. This means, you need to add this view into some existing screen (Activity or Fragment), provide data and launch the app on a device/emulator.</p><p>Now let’s add Compose preview for our custom Android view. We use AndroidView as a <a href="https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose">bridge between Compose Preview function and Android view</a>. Since AndroidView is a Compose function, we have this comfort to modify it with custom modifier (by adding background color and some padding), so that view looks better in preview. I’ve also added PreviewParam class as preview data wrapper, as only single parameter in Preview Compose function can be annotated with @PreviewParameter annotation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9666e240b6548ff68a7775880a9bb1c/href">https://medium.com/media/b9666e240b6548ff68a7775880a9bb1c/href</a></iframe><p>Now our preview looks way better — status badge has correct icon and color, as well as specification items are visible now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*V44rz5ogu7pajRQItwpcSw.png" /></figure><p>Let’s add more data variations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c373cd41496805afa5cb906022ed55eb/href">https://medium.com/media/c373cd41496805afa5cb906022ed55eb/href</a></iframe><p>Not only we get different view variations, but also able to spot a bug in our custom view – items are not constrained correctly. This is actually great, as we’ve spotted the bug on early development stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*rwupKKymFip2ma5dDW3lew.png" /></figure><p>I will leave finding the issue for reader as small exercise, but the final preview looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*eZx8dTJCKaWBgzI34FQZlA.png" /></figure><p>Here is a <a href="https://github.com/mirokolodii/AndroidComposePlayground/tree/main/preview">link to this code on GitHub</a>.</p><p><a href="https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose">Using Views in Compose | Jetpack Compose | Android Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b514e6e928d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switch from Java to Kotlin in 5 steps]]></title>
            <link>https://medium.com/@mkolodii/switch-from-java-to-kotlin-in-5-steps-8f61b0f4222d?source=rss-8c1f1fc5e868------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f61b0f4222d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[null-safety]]></category>
            <dc:creator><![CDATA[Myroslav Kolodii]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 07:36:01 GMT</pubDate>
            <atom:updated>2019-10-31T07:36:01.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaOff1oGqTa0is1OltT1uw.jpeg" /></figure><h3>#2 Null safety</h3><p>In Java all objects can hold a special <em>null</em> value. In fact, declaration of a variable of any reference type without specifically initializing it with some value by default will initialize it with a <em>null</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/271c14f39c0771c7c39650a2670c7b55/href">https://medium.com/media/271c14f39c0771c7c39650a2670c7b55/href</a></iframe><p>In Kotlin you need to specify explicitly, whether or not a variable can hold a <em>null</em> value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b13157aa28ef64eb11ac4ed037e4aac0/href">https://medium.com/media/b13157aa28ef64eb11ac4ed037e4aac0/href</a></iframe><p>Every type in Kotlin has a twin brother, which can hold a nullable value, and this is where a question mark (<strong>?</strong>) comes in places.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fae91559d008ee0f06f5945d9d3526cc/href">https://medium.com/media/fae91559d008ee0f06f5945d9d3526cc/href</a></iframe><p>The same is applicable for own-declared types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c00269a033cb8c9c221d62458c8ddbbf/href">https://medium.com/media/c00269a033cb8c9c221d62458c8ddbbf/href</a></iframe><p>It’s OK to assign a value of variable with non-null type to its nullable equivalent, but, to do the same in opposite direction, you need to check for <em>null</em> first.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0ee0500318f4ec95f801c1beccac2ca/href">https://medium.com/media/d0ee0500318f4ec95f801c1beccac2ca/href</a></iframe><p>On a first glance it looks like additional complication of having two types — nullable and non-nullable. So, what’s the reason of having this?</p><p>Having a possibility to specifically declare a type to be non-nullable can drastically eliminate <em>NullPointerExceptions</em> in your code. No need for <em>null</em> checks as well <em>(if someVar != null).</em></p><p>Here are some simple examples.</p><p>In Java primitive types can’t hold a <em>null</em> value. So, during unboxing a <em>null</em>, you’ll get a <em>NullPointerException</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93b2c8eb7983c87f7e05b31b6bd3ea65/href">https://medium.com/media/93b2c8eb7983c87f7e05b31b6bd3ea65/href</a></iframe><p>On contrary, Kotlin doesn’t have primitive types (so no unboxing). You can’t assign variable of nullable type to non-nullable one without first checking for nullability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85cb9da668cfe391149e7c5e8ace9d3e/href">https://medium.com/media/85cb9da668cfe391149e7c5e8ace9d3e/href</a></iframe><p>Another example is checking for equality. Below Java code will crash with a <em>NullPointerException</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2920cd922b3fc3370534bcaab2d20a/href">https://medium.com/media/9c2920cd922b3fc3370534bcaab2d20a/href</a></iframe><p>In Kotlin it is recommended to use <strong><em>== </em></strong>operation to check for structural equality, which can handle <em>null</em> values just fine. (Important: don’t confuse Kotlin’s <strong>==</strong> operation to the Java’s one. If you want to check for referential equality, use <strong>===</strong> operation instead. More information is <a href="https://gist.github.com/mirokolodii/37f2b6a9057d9311be5a8af8cfea3368">here</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f4aeb074afd8bf93c0bba4542bfb438/href">https://medium.com/media/9f4aeb074afd8bf93c0bba4542bfb438/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f61b0f4222d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>