{"id":13473746,"url":"https://github.com/myinnos/Kotlin-Example","last_synced_at":"2025-03-26T19:34:40.132Z","repository":{"id":37743335,"uuid":"78503735","full_name":"myinnos/Kotlin-Example","owner":"myinnos","description":"An example for who are all going to start learning Kotlin programming language to develop Android application.","archived":true,"fork":false,"pushed_at":"2019-07-31T06:05:19.000Z","size":3446,"stargazers_count":57,"open_issues_count":0,"forks_count":21,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-10-30T06:33:25.417Z","etag":null,"topics":["android-application","android-developers","anko","java","kotlin","kotlin-android","kotlin-library","kotlin-plugin","splashscreen"],"latest_commit_sha":null,"homepage":"https://myinnos.github.io/Kotlin-Example/","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/myinnos.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"custom":["https://play.google.com/store/apps/details?id=in.myinnos.supportdev"]}},"created_at":"2017-01-10T06:15:43.000Z","updated_at":"2024-03-14T06:41:07.000Z","dependencies_parsed_at":"2022-08-24T16:21:53.765Z","dependency_job_id":null,"html_url":"https://github.com/myinnos/Kotlin-Example","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myinnos%2FKotlin-Example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myinnos%2FKotlin-Example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myinnos%2FKotlin-Example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/myinnos%2FKotlin-Example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/myinnos","download_url":"https://codeload.github.com/myinnos/Kotlin-Example/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245722910,"owners_count":20661849,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["android-application","android-developers","anko","java","kotlin","kotlin-android","kotlin-library","kotlin-plugin","splashscreen"],"created_at":"2024-07-31T16:01:06.436Z","updated_at":"2025-03-26T19:34:38.143Z","avatar_url":"https://github.com/myinnos.png","language":"Kotlin","readme":"# [Kotlin Example](https://myinnos.github.io/Kotlin-Example/ \"View Website - Kotlin Example\")\n\nHere is an example for who are all going to start learning Kotlin programming language to develop  Android application.\n\nFirst check [this](https://play.google.com/store/apps/details?id=in.myinnos.kotlinexample \"Kotlin Example - Android\") example APK to understand basic steps easily. I enjoyed a lot while doing this tutorial, If your Java developer you can play with this. *Happy Coding!*\n\n[![Get it on Google Play](https://s19.postimg.org/5wroedueb/ic_launcher.png)](https://play.google.com/store/apps/details?id=in.myinnos.kotlinexample)\n\n[Kotlin](https://kotlinlang.org/ \"Kotlin\") is very lightweight, its run-time library is under 400K minus the ProGuard minification. Also, installation is very simple. All you have to do is browse the plugin repository and get the official Kotlin plugin. You also had to install Kotlin Android Extensions as well, required for Android of course, but not until recently it has been merged with the Kotlin plugin and is now obsolete.\n\n\n\tSettings \u003e Plugins \u003e Browse Repositories \u003e Search Kotlin and install\n\nTo configure Kotlin in your project, convert any source file to Kotlin first.\n\n\n\tSelect a Java file \u003e Hit Ctrl+Shift+A \u003e “convert to kotlin” Hit enter\n    \nTake a look [here](https://kotlinlang.org/docs/tutorials/kotlin-android.html \"Kotlin Tutorial - Android\") for screenshots and brief explanation.   \n\n##### Android UI With Anko\n[Anko](https://github.com/Kotlin/anko \"Anko\") is a library made in Kotlin that is a great utility for Android development. It consists of DSL wrappers and other nice extensions that make development easier. The prime value of Anko is that it allows you to embed UI layouts inside your source code, which makes it type-safe and allows programmatic transformation.\n\nJust a brief example. Here is a \"hello world\" written with Anko:\n\n```java\nverticalLayout {\n    val name = editText()\n    button(\"Say Hello\") {\n        onClick { toast(\"Hello, ${name.text}!\") }\n    }\n}\n```\nStarted by letting Gradle know some dependencies, one set for the Support Library, another for the Kotlin run-time, and one more set for Anko obviously.\n\n###### Reference those dependencies\n```java\nfinal SUPPORT_VERSION = '23.3.0'\nfinal ANKO_VERSION = '0.8.3'\n\ndependencies {\n    compile fileTree(include: ['*.jar'], dir: 'libs')\n    compile \"com.android.support:appcompat-v7:${SUPPORT_VERSION}\"\n    compile \"com.android.support:recyclerview-v7:${SUPPORT_VERSION}\"\n    compile \"org.jetbrains.anko:anko-sdk15:${ANKO_VERSION}\"\n    compile \"org.jetbrains.anko:anko-appcompat-v7:${ANKO_VERSION}\"\n    compile \"org.jetbrains.anko:anko-recyclerview-v7:${ANKO_VERSION}\"\n    compile \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\n}\n```\nOne thing to be noted here, the Anko base library, i.e., the anko-sdk* lib, you should add on the basis of your minimum SDK version and the rest of the other dependencies, you add on the basis of the Support Library that you wish to extend with Anko. For instance, add anko-design for design, which is from the Support Library.\n\n\n## Example\n\n ![Kotlin Example - Splashscreen](https://s19.postimg.org/6h6ph2nmr/Kotlin_Example_Splashscreen.png) ![Kotlin Example - MainScreen](https://s19.postimg.org/8j76vbllv/Kotlin_Example_Main_Screen.png) ![Kotlin Example - Menu](https://s19.postimg.org/4o3ssr2g3/Kotlin_Example_Menu.png) ![Kotlin Example - WebView](https://s19.postimg.org/ol9q1plb7/Kotlin_Example_Web_View.png)\n\n#### SplashScreenActivity.kt\n\nSplash screen is one of the friend for android developers will see most of the times this screen while developing interesting concepts. Here you can see how Splashscreen code looks interms of Kotlin.\n\n*Note: Here i followed [this](https://www.bignerdranch.com/blog/splash-screens-the-right-way/ \"Splash screens the right way\") tutorial to create express splashscreen.*\n\n```java\nclass : Activity() {\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n\n        // Start main activity\n        startActivity(Intent(this, MainActivity::class.java))\n\n        // close this activity\n        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out)\n        finish()\n    }\n\n}\n```\n\n###### Some Awesome methods/functions\n\n##### Variable declaration. int/string/boolean\n\n```java\nvar EMAIL_ID = \"contact@myinnos.in\"\n```\n\n##### To open Web URL\n\n```java\nbrowse(GIT_HUB_URL)\n```\n\n##### setText function\n\n```java\ntvHeader.text = HEADER_TEXT\n```\n\n##### Hint to Edit Text\n\n```java\netName.hint = EDIT_TEXT_NAME_HINT\n```\n\n##### Toast \n\n```java\ntoast(\"Activity restarted!\")\n```\n\n##### Email Intent  \n\n```java\nemail(EMAIL_ID, \"subject\")\n```\n\n##### Share Intent \n\n```java\nshare(\"text\")\n```\n\n##### Function declaration, function to get text length of edit text \n\n```java\nfun checkTextLength(editText: EditText): Boolean {\n        var length = editText.length()\n        if (length \u003e 0)\n            return true\n        else\n            return false\n}\n```\n\n##### onClick funtion\n\n```java\nbtDone.onClick {\n            hideKeyboard()\n            if (!checkTextLength(etName) || !checkTextLength(etMobile))\n                toast(\"Fields cannot be empty!\")\n            else\n                onButtonClicks()\n}\n```\n\n##### Dialog Aleart Box \n\n```java\nfun openAlertDialog(name: String, phoneNumber: String) {\n\n        val countries = listOf(\"Russia\", \"India\", \"USA\", \"Japan\", \"China\")\n\n        selector(\"Where are you from?\", countries) { i -\u003e\n            alert(\"One more thing! You have entered this number \" + phoneNumber, name + \"! So you're living in ${countries[i]}, right?\")            {\n                customView {\n                    verticalLayout {\n                        positiveButton(\"AWESOME!\") {\n                            longToast(\"Thank you!\")\n                        }\n                    }\n                }\n\n            }.show()\n}\n```\n\n##### Initializing menu options \n\n```java\n override fun onCreateOptionsMenu(menu: Menu?): Boolean {\n        getMenuInflater().inflate(R.menu.menu_main, menu)\n        return true\n    }\n\n override fun onOptionsItemSelected(item: MenuItem?): Boolean {\n        val id = item!!.getItemId()\n        //noinspection SimplifiableIfStatement\n        if (id == R.id.action_rate) {\n            // opining browser intent\n            browse(PLAY_STORE_URL)\n            return true\n        }\n        return super.onOptionsItemSelected(item)\n    }\n```\n\n#### MainActivity.kt\n\nMain screen, The wall where Android developer paint and repair. Here you can observe the code how plain and simple. Basically i started loving Kotlin while writing this class.  \n\n*Note: I used [Google Custom Tabs](https://developer.chrome.com/multidevice/android/customtabs \"Google Custom Tabs\") library to understand how third party java libraries will work with Kotlin.*\n\n```java\nclass MainActivity : AppCompatActivity() {\n\n    var HEADER_TEXT = \"You can try awesome example!\"\n    var EDIT_TEXT_NAME_HINT = \"enter name\"\n    var EDIT_TEXT_NUMBER_HINT = \"enter number\"\n    var EMAIL_ID = \"contact@myinnos.in\"\n    var GIT_HUB_URL = \"https://github.com/myinnos/Kotlin-Example\"\n    var GIT_HUB_WEB_URL = \"https://myinnos.github.io/Kotlin-Example/\";\n    var PLAY_STORE_URL = \"market://details?id=\" + BuildConfig.APPLICATION_ID\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n\n        // setting header text\n        tvHeader.text = HEADER_TEXT\n        // setting hint for edit text\n        etName.hint = EDIT_TEXT_NAME_HINT\n        etMobile.hint = EDIT_TEXT_NUMBER_HINT\n\n        // setting drawable image to image view\n        imageView.resources.getDrawable(R.mipmap.ic_launcher)\n\n        // onclick event for image view to restart activity (Intent function)\n        imageView.onClick {\n            startActivity\u003cSplashScreenActivity\u003e()\n            finish()\n            toast(\"Activity restarted!\")\n        }\n\n        // onclick event for button\n        btDone.onClick {\n            hideKeyboard()\n            if (!checkTextLength(etName) || !checkTextLength(etMobile))\n                toast(\"Fields cannot be empty!\")\n            else\n                onButtonClicks()\n        }\n\n        btGitHubLink.onClick {\n            // opining browser intent\n            browse(GIT_HUB_URL)\n        }\n\n        btTutorial.onClick {\n            // google custom tabs\n            val builder = CustomTabsIntent.Builder()\n            builder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary))\n            val customTabsIntent = builder.build()\n            customTabsIntent.launchUrl(this, Uri.parse(GIT_HUB_WEB_URL))\n        }\n    }\n\n    // function to get text from edit text\n    fun EditText.textValue(): String {\n        return text.toString()\n    }\n\n    // function to get text length of edit text\n    fun checkTextLength(editText: EditText): Boolean {\n\n        var length = editText.length()\n\n        if (length \u003e 0)\n            return true\n        else\n            return false\n    }\n\n    // function to hide keyboard\n    fun hideKeyboard() {\n        try {\n            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager\n            imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)\n        } catch (e: Exception) {\n            // TODO: handle exception\n        }\n\n    }\n\n    fun onButtonClicks() {\n        //using function\n        val phoneNumber = etMobile.textValue()\n        // direct access\n        val name = etName.text.toString()\n        // calling alert dialog\n        openAlertDialog(name, phoneNumber)\n    }\n\n    fun openAlertDialog(name: String, phoneNumber: String) {\n\n        val countries = listOf(\"Russia\", \"India\", \"USA\", \"Japan\", \"China\")\n\n        selector(\"Where are you from?\", countries) { i -\u003e\n            //toast(\"So you're living in ${countries[i]}, right?\")\n            alert(\"One more thing! You have entered this number \" + phoneNumber, name + \"! So you're living in ${countries[i]}, right?\") {\n                customView {\n                    verticalLayout {\n                        positiveButton(\"AWESOME!\") {\n                            longToast(\"Thank you!\")\n                        }\n                    }\n                }\n\n            }.show()\n\n        }\n    }\n\n    // Initializing menu options\n    override fun onCreateOptionsMenu(menu: Menu?): Boolean {\n        // Inflate the menu; this adds items to the action bar if it is present.\n        getMenuInflater().inflate(R.menu.menu_main, menu)\n        return true\n    }\n\n    override fun onOptionsItemSelected(item: MenuItem?): Boolean {\n        // Handle action bar item clicks here. The action bar will\n        // automatically handle clicks on the Home/Up button, so long\n        // as you specify a parent activity in AndroidManifest.xml.\n        val id = item!!.getItemId()\n\n        //noinspection SimplifiableIfStatement\n        if (id == R.id.action_share) {\n            // sharing intent\n            share(getString(R.string.share_text) + BuildConfig.APPLICATION_ID,\n                    getString(R.string.app_name))\n            return true\n        } else if (id == R.id.action_feedback) {\n            // email intent\n            email(EMAIL_ID, getString(R.string.app_name))\n            return true\n        } else if (id == R.id.action_rate) {\n            // opining browser intent\n            browse(PLAY_STORE_URL)\n            return true\n        }\n\n        return super.onOptionsItemSelected(item)\n    }\n}\n```\n\n### Conclusion\nKotlin is overall a great language. It is much less verbose than Java, and has an excellent standard library that removes the need to use a lot of the libraries that make Java life bearable. Converting an app from Java to Kotlin is made much easier thanks to automated syntax conversion, and the result is almost always an improvement. If you’re an Android developer, you owe it to yourself to give it a try.\n\n##### Any Queries? or Feedback, please let me know by opening a [new issue](https://github.com/myinnos/Kotlin-Example/issues/new)!\n\n## Contact\n\n### Prabhakar Thota\n* :globe_with_meridians: Website: [myinnos.in](http://www.myinnos.in \"Prabhakar Thota\")\n* :email: e-mail: contact@myinnos.in\n* :mag_right: LinkedIn: [PrabhakarThota](https://www.linkedin.com/in/prabhakarthota \"Prabhakar Thota on LinkedIn\")\n* :thumbsup: Twitter: [@myinnos](https://twitter.com/myinnos \"Prabhakar Thota on twitter\")\n\nLicense\n-------\n\n    Copyright 2017 MyInnos\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n","funding_links":["https://play.google.com/store/apps/details?id=in.myinnos.supportdev"],"categories":["Kotlin","App / Demo"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmyinnos%2FKotlin-Example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmyinnos%2FKotlin-Example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmyinnos%2FKotlin-Example/lists"}