Category: Uncategorized

How to access a view programmatically using findViewById – Kotlin Android

In this Android Tutorial, we shall learn how to access a View programmatically using findViewById(int id) method in Kotlin Android with examples for EditText, Button, etc.

findViewById(int id) is very useful function to access or update properties of Views (Direct and Indirect Classes of android.view.View). Some of the regularly used Views are LinearLayout, TextView, Button, EditText, ImageView etc.

Access a view programmatically using findViewById method

Access a view programmatically using findViewById method - Kotlin Android Tutorial - www.tutorialkart.com

To find a view programmatically, the View (LinearLayout / TextView / Button / ImageView / EditText etc.) should have been set with an id in the layout xml file as shown below :

And in the Kotlin file, the View can be assigned to a variable using findViewById method as shown below :

Reference of Button view is loaded to the variable, btn_submit. The reference could be used to access or modify the properties of the view.

We shall look into an example Login Form Kotlin Android Project, where there are four views that we access programmatically, and assign an OnClickListener to Button.

Following is the login form activity layout xml file that has views with id s assigned.

And in the following Kotlin file, we shall access those views with ids et_user_name, et_password, btn_reset and btn_submit.

Dynamically change Button background in Kotlin Android

In this Android Tutorial, we shall learn to dynamically change button background in Kotlin Android.

There could be scenarios where you might need to change the background of a button to show a state of the application or status of an update or status of a player, etc.

setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.

Useful links
To set a drawable background to button : Custom design for Button background
To set a onClickListener to button : Button setOnClickListener

Example – Dynamically change button background in Kotlin Android

In the following Kotlin Android Example, we shall create a button in layout xml and dynamically change its background on the button click using Button OnClickListener.

layout xml file : activity_change_button_background.xml

Kotlin Activity file : ChangeButtonBackground.kt

/app/src/main/res/drawable/btn_center_gradient.xml

/app/src/main/res/drawable/btn_oval_gradient.xml

Following are the screenshots of the application :
Click on the button to change the background.

Dynamically change button background in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com

Button with initial backgroud

Dynamically change button background in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com

Button background changed on button click

How to create custom design for Button background in Kotlin Android

There is a default style for a Button in Android, but it may not fit your application theme. In this Android Tutorial, we shall present you on ways to create custom design for Button background. Following screenshot will give a quick look of custom Button designs that are going to be created in this tutorial.

Create custom design for Button background in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com

Create custom design for Button in Kotlin Android

Create custom design for Button background in Kotlin Android

Following are the steps in creating a custom background drawable for a Button in Android :

  1. Create a drawable xml file in /app/res/drawable/ folder. Say button_background.xml
  2. Mention the shape of drawable, and its properties in the xml. An example is provided below :
  3. Create a button in the layout xml file and provide the drawable, button_background.xml as background. Example code snippet is shown below :
  4. You may change some properties of the Button like padding, margin, textColor etc., for a proper look and to suit your application theme.

Example Kotlin Android Application details for customizing Button Backgrounds

Following are the layout and Activity file contents that could generate the buttons shown in the starting of the tutorial.

activity_custom_buttonn.xml

 

CustomButtonActivity.kt

 

Login Form Example in Kotlin Android

In this Android Tutorial, we shall learn how to implement a Login Form in an Android Activity with the help of an Example Android Application.

The Login Form shall include two edit text views for user name and password. There shall be a reset button to reset the fields and a submit button to read the values for user name and password and further process them. OnClickListeners are setup for reset and submit buttons.

A mock-up screenshot of the Login Form Example in Kotlin Android would be as shown below :

Login Form Example in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com

Login Form Example in Kotlin Android

Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content, which will help you create a Login Form.

 

 

Screenshots for Login Form Example in Kotlin Android

Login Form Example in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com

Login Form Example in Kotlin Android

UserName and Password are entered into fields - Kotlin Android Tutorial - www.tutorialkart.com

UserName and Password are entered into fields

Click on Submit - Toast User Name - Kotlin Android Tutorial - www.tutorialkart.com

Click on Submit – Toast User Name

Kotlin vs Java in Android Application Development

Kotlin vs Java in Android Application Development considering features of individual languages and their impact in coding.

Kotlin vs Java in Android Application Development - Kotlin Android Tutorial - www.tutorialkart.com

Kotlin vs Java in Android Application Development

Following are the differences between Kotlin and Java in Android Application Development :

PropertyJavaKotlin
Android Application CodeNot ConciseRelatively Concise
Handle NullPointerExceptionYou have to explicitly handle this exception all the timesKotlin Null Safety feature could be used or you may handle it explicitly.
Extend a class with new functionalityYou may have to create a new class that extends the class and the new functionality should be added in new class. New class reference should be used in your code. It becomes messy.Kotlin extension functions could be used to extend the functionality of a class and use the same class name in your code without and mess and fuss.
Handle high computation tasks without blocking UI threadA background thread (like AsyncTask) has to be used. And if multiple such threads are background tasks are required, managing multiple threads may become difficult.You may create coroutines. Coroutines perform high computationally tasks without blocking main thread, but suspending execution at a certain point. Coroutines being stackless, have a lower memory usage.
Checked ExceptionsYou may need to catch and handle these exceptions. However, this may make your code robust.Kotlin does not have checked Exception, hence no need to catch an exception. Code becomes clear and concise.
Multiple InheritanceNot supported.Kotlin’s Class Delegation could be used as an alternative to multiple inheritance.
Implicit widening conversionJava supports implicit widening conversion like you may assign a byte value to an int, an int value to a double.Kotlin does not support implicit widening conversion, Atleast as of now. You may need to type cast for any conversion.
Android Studio SupportAn officially supported language.Also, an officially supported language, latest addition to the list.
Data ClassesGetters, Setters, equals(), hashCode() and toString()  have to be explicity written.Getters, Setters, equals(), hashCode() and toString() are implicit. No need to write them separately.

With these differences at a glance, you may choose either Kotlin or Java for Android Application Development.

 

Conclusion :

In this Android Tutorial, we have presented the differences between Java and Kotlin for various aspects, to help choose a programming language for Android Application Development.

How to use Java 8 features in Android Studio ?

Android Studio 3.0 (by 25th July 2017) only has a preview (canary) version available. Like the previous versions (2.3.x) it supports all Java 7 features and some of the Java 8 features. These subset of Java 8 features supported, vary by platform version. During your Android application development, it is not mandatory that you use Java 8 features, but compiling using Java 8 is mandatory. And in the ongoing tutorial, we shall learn how to use Java 8 features in Android Studio that are builtin.

The Jack tool chain that has been introduced in Android Studio 2.1 and higher is depreciated. Now Android Studio 3.0 has a built in support for a subset of Java 8 features. So, if you have been using Jack toolchain, it is advised to disable Jack toolchain and use the default toolchain provided by Android Studio 3.0 + for an improved Java 8 builtin support.

Use Java 8 features in Android Studio - www.tutorialkart.com

Use default Java 8 features in Android Studio

To disable Jack toolchain from your Android Application, remove the jackOptions snippet from defaultConfig block in build.gradle file.

To start using Java 8 features in your Android Application, update Android plugin to 3.0.0-alpha1 or higher and add the following compileOptions to build.gradle file in your app folder.

Following are the Java 8 features supported by all sdk versions (you may keep any minSdkVersion) :

  • Lambda expressions (Exception : All values captured by the lambda should be serializable.)
  • Method References
  • Type Annotations (Exception : ElementType.TYPE_USE and ElementType.TYPE_PARAMETER are supported for sdk version 24+)
  • Default and Static interface methods
  • Repeating annotations

And following are the Java 8 APIs that are supported with a minSdkVersion of 24 (or higher) :

  • java.lang.annotation.Repeatable
  • AnnotatedElement.getAnnotationsByType(Class)
  • java.util.stream
  • java.lang.FunctionalInterface
  • java.lang.reflect.Method.isDefault()
  • java.util.function

If you experience any issues with the latest Java 8 features, you may disable it by disabling Desugar in your gradle.properties file as shown below :

 

Conclusion :

In this Android Tutorial, we have learnt a way for how to use Java 8 features in Android Application development.

How to set OnClickListener for ImageView in Kotlin Android

In Android, ImageView is a child class of View, and hence the method setOnClickListener() could be used on the object of type ImageView. When OnClickListener is set to ImageView, a click on the ImageView triggers the action and code inside setOnClickListener method is executed.

Following is quick look into code to set OnClickListener for ImageView in Kotlin Android :

In this Android Tutorial, we shall look into the layout xml file and Activity(Kotlin) file to set OnClickListener for a ImageView. Create an Android Application with Kotlin Support and replace activity_main.xml and MainActivity.kt with the following content.

activity_main.xml

MainActivity.kt

Keep an image in the folder app/res/drawabale/ with name image1.png. This image has been given as the src (source) to ImageView in the activity_main.xml layout file.

Following are the screenshots to demonstrate the setOnClickListener for ImageView :

Activity with ImageView - Kotlin Android Tutorial - www.tutorialkart.com

ImageView in Activity set with OnClickListener

set OnClickListener for ImageView in Kotlin Android - Tutorial - www.tutorialkart.com

Click on ImageView to trigger OnClickListener method.

 

How to set OnClickListener for TextView in Kotlin Android

In Android, TextView is a child class of View, and hence can use the method setOnClickListener() on the object of TextView.

Following is quick look into code to set OnClickListener for TextView in Kotlin Programming :

In this Android Tutorial, we shall look into the layout xml file and Activity(Kotlin file) to set OnClickListener for a TextView. Create an Android Application with Kotlin Support  and replace activity_main.xml and MainActivity.kt with the following content.

Following are the screenshots to demonstrate the setOnClickListener for TextView :

MainActivity with TextView "Click Me" - Kotlin Android Tutorial - www.tutorialkart.com

MainActivity with TextView “Click Me”

Set OnClickListener for TextView in Kotlin Android - Tutorial - www.tutorialkart.com

OnClickListener set for TextView