Pages

Wednesday, June 7, 2017

Alertdialog in Android using Kotlin

In this Post, I show you how to display an alert dialog in android using Kotlin and Anko library. In this Demo app will create simple Alert and Alert with Action Button.

Application developing tools :

Android Studio 3.0 Canary 3
Android 25 version
Build Tools Version - 25.0.2
Kotlin Version - 1.1.2-4
Anko Library Version - 0.10.1

Follow Steps :
1. Create New Application
2. Apply plugin and Add dependency in build.gradle file
3. Add button in layout file
4. Add code in Activity

Kotlin Android Extensions plugin (automatically bundled into the Kotlin plugin in Android Studio) solves the issue: replacing findViewById with a brief and straightforward code.

Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java.
we using Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on;.

In General, Simple Text Alert with one button.

 val simpleAlert = AlertDialog.Builder(this@MainActivity).create()
        simpleAlert.setTitle("Alert")
        simpleAlert.setMessage("Show simple Alert")

        simpleAlert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on OK", Toast.LENGTH_SHORT).show()
        })

        simpleAlert.show()

Anko Library provide simple way to show simple text Alert with one button.
 alert("Show simple Alert","Alert") {
            positiveButton("OK") {
                toast("You clicked on OK")
            }
        }.show()


let's start!

Create New Application






appyly plugin and add dependency in app-module build.gradle file

 

Apply Plugin
apply plugin: 'kotlin-android-extensions'
Add Dependency (Anko Commons Library)
    compile "org.jetbrains.anko:anko-commons:0.10.1"

Layout Files : main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.limbani.alertdialogdemo.MainActivity">

    <Button
        android:id="@+id/simpleAlert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Simple Alert" />

    <Button
        android:id="@+id/alertTwoButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with two Button" />

    <Button
        android:id="@+id/alertThreeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with three Button" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="Using Anko Library Example" />

    <Button
        android:id="@+id/ankoSimpleAlert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Simple Alert" />

    <Button
        android:id="@+id/ankoAlertTwoButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with two Button" />

    <Button
        android:id="@+id/ankoAlertThreeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with three Button" />
</LinearLayout>

Activity :


MainActivity.kt here first three button show to simple way to show alert dialog and below three button show the alert dialog using Anko Library
package com.limbani.alertdialogdemo

import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        simpleAlert.setOnClickListener {
            showSimpleAlert()
        }

        alertTwoButton.setOnClickListener {
            showAlertWithTwoButton()
        }

        alertThreeButton.setOnClickListener {
            showAlertWithThreeButton()
        }

        //Anko Example Button here
        ankoSimpleAlert.setOnClickListener {
            ankoShowSimpleAlert()
        }

        ankoAlertTwoButton.setOnClickListener {
            ankoShowAlertWithTwoButton()
        }

        ankoAlertThreeButton.setOnClickListener {
            ankoShowAlertWithThreeButton()
        }
    }

    //Anko Library Example code here
    private fun ankoShowAlertWithThreeButton() {
        alert("Show Alert with three Button", "Alert") {
            positiveButton("POSITIVE") {
                toast("You clicked on POSITIVE Button")
            }
            negativeButton("NEGATIVE") {
                toast("You clicked on NEGATIVE Button")
            }
            neutralPressed("NEUTRAL") {
                toast("You clicked on NEUTRAL Button")
            }
        }.show()
    }

    private fun ankoShowAlertWithTwoButton() {
        alert("how Alert with two Button","Alert") {
            positiveButton("YES") {
                toast("You clicked on YES")
            }
            negativeButton("NO") {
                toast("You clicked on NO")
            }
        }.show()
    }

    private fun ankoShowSimpleAlert() {
        alert("Show simple Alert","Alert") {
            positiveButton("OK") {
                toast("You clicked on OK")
            }
        }.show()
    }

    //General code here
    private fun showAlertWithThreeButton() {
        val alertDilog = AlertDialog.Builder(this@MainActivity).create()
        alertDilog.setTitle("Alert")
        alertDilog.setMessage("Show Alert with three Button")

        alertDilog.setButton(AlertDialog.BUTTON_POSITIVE, "POSITIVE", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on POSITIVE Button", Toast.LENGTH_SHORT).show()
        })

        alertDilog.setButton(AlertDialog.BUTTON_NEGATIVE, "NEGATIVE", {
            dialogInterface, j ->
            Toast.makeText(applicationContext, "You clicked on NEGATIVE Button", Toast.LENGTH_SHORT).show()
        })
        alertDilog.setButton(AlertDialog.BUTTON_NEUTRAL, "NEUTRAL", {
            dialogInterface, k ->
            Toast.makeText(applicationContext, "You clicked on NEUTRAL Button", Toast.LENGTH_SHORT).show()
        })

        alertDilog.show()
    }

    private fun showAlertWithTwoButton() {
        val alertDilog = AlertDialog.Builder(this@MainActivity).create()
        alertDilog.setTitle("Alert")
        alertDilog.setMessage("Show Alert with two Button")

        alertDilog.setButton(AlertDialog.BUTTON_POSITIVE, "YES", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on YES", Toast.LENGTH_SHORT).show()
        })

        alertDilog.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on NO", Toast.LENGTH_SHORT).show()
        })

        alertDilog.show()
    }

    private fun showSimpleAlert() {

        val simpleAlert = AlertDialog.Builder(this@MainActivity).create()
        simpleAlert.setTitle("Alert")
        simpleAlert.setMessage("Show simple Alert")

        simpleAlert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on OK", Toast.LENGTH_SHORT).show()
        })

        simpleAlert.show()
    }
}

Test (Screenshot)




Resource
https://kotlinlang.org
Android Developer Blog
Anko Library
 
Thanks for reading this post.
Enjoy:)

Tuesday, June 6, 2017

Hello World App in Kotlin Android

Kotlin is a programing language and now officially support for Android Application development. For more Details for Kotlin check Android Developer Blog and Kotlin Documentation.
The Kotlin plug-in is now bundled with Android Studio 3.0. Also available for older version see my last post how to setup Kotlin Plugin in Android Studio.

Here simple Example app of the Say Hello World in Kotlin language. In App show one TextView and One Button click to show Toast to Say Hello World. Follow below steps to run first Hello World App.

Create New Application


Open Android Studio File>New>New Project



Select Include Kotlin support check box and click Next button.(This option available in Android Studio 3.0 Version.)


Select Phone and Tablet, Minimum SDK version and Click Next button.


Select Empty Activity and click Next button.


If you want to change Activity name then change here otherwise go with default MainActivity name and click Finish Button

After you need to check Kotlin plug-in in both root project and app-model build.gradle file.
root project build.gradle
 
buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


App-model build.gradle file add two apply plugin 'kotlin-android', 'kotlin-android-extensions' and add one dependency compile "org.jetbrains.anko:anko-commons:0.10.1".

Kotlin Android Extensions is a compiler extension that allows you to get rid of findViewById() calls in your code and to replace them with synthetic compiler-generated properties.

org.jetbrains.anko:anko-commons:0.10.1 - Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java. Anko Commons is a lightweight library full of helpers for intents, dialogs, logging and so on;
 
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.limbani.helloworld"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:25.3.1'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "org.jetbrains.anko:anko-commons:0.10.1"
}

MainActivity.kt file

package com.limbani.helloworld

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_hello.setOnClickListener {
            toast("Say Hello World")
            // For long toast
            // longToast("Say Hello World")
            printButtonClickLog()
        }
    }

    private fun printButtonClickLog() {
        Log.i("MainActivity", "Hello Button Clicked")
    }
}

activity_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.limbani.helloworld.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="Hello World!"
        android:textSize="20sp" />

    <Button
        android:id="@+id/btn_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Say Hello"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.helloworld">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshot of the app.


Resource
https://kotlinlang.org
Android Developer Blog
Anko Library
 
Thanks for reading this post.

Setup Kotlin Plugin for Android Studio 2.3

AndroidDev annouce officially adding support for the Kotlin programing language. Check here Android Developer Blog.

The Kotlin plug-in is now bundled with Android Studio 3.0. Kotlin was developed by JetBrains, the same people who created IntelliJ. Also Kotlin pluging available for Android Studio 2.3.2 version. See below how to add plugin Kotlin in Android Studio lower vsersion.

Let's Start to setup

Install Kotlin Plugin for Android Studio


In Windows PC : Open File>Setting>Plugins>Browse Repositories (Preferences > Plugins > Browse Repositories). Search Kotlin and Install.

 
When the install is complete, you will need to restart Android Studio to apply the new plugin.

Apply Kotlin Plugin to the project


First of all create a new Android Project. File>New>New Project and follow through project creation steps.

Next step to apply the Kotlin Plugin to both build.gradle files at the Project level and app-module level. There is an automated tools to do this, but sometimes the manual process of applying the plugin in our build.gradle files.

First we need to add the plugin to the root project build.gradle.

 
buildscript {
    ext.kotlin_version = "1.1.2-4" // replace with the latest (stable) version: https://github.com/JetBrains/kotlin/releases/latest

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Second we need to add the plugin to the app-module build.gradle. To add apply plugin : kotlin-android in build.gradle file

  apply plugin: 'com.android.application'
  apply plugin: 'kotlin-android' // apply kotlin android plugin

Convert Java Code to Kotlin


We setup all we need, but our Empty Activity still in java. Here show how to convert java file to Kotline. Way to convert java file to Koitlin Select Code>Convert Java File to Kotlin or use shortcut - control + Alt + Shift + K  (Replace control to Command if you are using MAC)

MainActivity.java
package com.limbani.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

After converting code to Kotlin. MainActivity.kt look like below
package com.limbani.helloworld

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Thanks for reading this post. I will be writing tutorial for Kotlin language.

Resource
https://kotlinlang.org
Android Developer Blog