course on Kotlin Android App Development, View Pager 2 – Screen Composition with Swipe Navigation

When developing Android apps, a feature that allows users to swipe through multiple pages is very useful.
To facilitate this, Google provides a component called ViewPager2.
In this tutorial, we will implement a simple app using ViewPager2 and explain the basic concepts and code in detail.

1. What is ViewPager2?

ViewPager2 is a UI component that allows users to swipe through multiple pages.
The main features of ViewPager2 are as follows:

  • Support for vertical and horizontal swiping
  • Support for Fragment and RecyclerView
  • Ability to set page transition effects

2. Setting up ViewPager2

To use ViewPager2, you need to add a dependency to your Gradle file.
Add the following line to your build.gradle file:

        dependencies {
            implementation "androidx.viewpager2:viewpager2:1.1.0"
        }
    

Let’s write the XML layout file needed to use ViewPager2.

2.1. XML Layout

Below is an example of a basic layout that includes ViewPager2.

        <?xml version="1.0" encoding="utf-8"?>
        <androidx.constraintlayout.widget.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=".MainActivity">

            <androidx.viewpager2.widget.ViewPager2
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>
        </androidx.constraintlayout.widget.ConstraintLayout>
    

3. Implementing ViewPager2 Adapter

ViewPager2 requires an adapter to display pages.
Below is a simple example of adapter implementation. This adapter uses custom Fragments to create each page.

3.1. Creating Fragment

First, create a Fragment class that represents each page.

        class CustomFragment : Fragment() {

            override fun onCreateView(
                inflater: LayoutInflater, container: ViewGroup?,
                savedInstanceState: Bundle?
            ): View? {
                val view = inflater.inflate(R.layout.fragment_custom, container, false)
                return view
            }
        }
    

3.2. Implementing Fragment Adapter

Next, implement the adapter by inheriting from FragmentStateAdapter.

        class ViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {

            override fun getItemCount(): Int {
                return 3 // Number of pages
            }

            override fun createFragment(position: Int): Fragment {
                return CustomFragment() // Return a different Fragment for each page
            }
        }
    

4. Setting up MainActivity

Now, let’s connect ViewPager2 and the adapter in MainActivity.

        class MainActivity : AppCompatActivity() {

            private lateinit var viewPager: ViewPager2

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

                viewPager = findViewById(R.id.viewPager)
                viewPager.adapter = ViewPagerAdapter(this)
            }
        }
    

5. Configuring Fragment Layout

Now, let’s configure the layout to be used in each Fragment.
In this example, we will simply display text.

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello, ViewPager2!"
                android:textSize="24sp"/>

        </LinearLayout>
    

6. Adding Swipe Page Transition Effects

ViewPager2 applies swipe animations by default, but you can customize it to apply various page transition effects.

        class ViewPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) {

            // ... existing code ...

            override fun createFragment(position: Int): Fragment {
                // You can return a different Fragment based on position to vary page content
                return when (position) {
                    0 -> FirstFragment()
                    1 -> SecondFragment()
                    else -> ThirdFragment()
                }
            }
        }
    

Here, you can define your desired page transition effect and apply it using ViewPager2’s
setPageTransformer method.

        viewPager.setPageTransformer { page, position ->
            page.alpha = 0f
            if (position >= -1 && position <= 1) { // [-1,1]
                page.alpha = 1 - Math.abs(position)
            }
        }
    

7. Conclusion

In this tutorial, we learned how to configure multiple swipable pages using ViewPager2.
You can enhance user experience by utilizing various page transition effects.
You can develop a richer app by adding additional features or integrating with other UI components.

Enjoy the joy of Android development!

kotlin android app development course, view class

In Android app development, the View class is the most fundamental element that makes up the UI. All elements that allow users to interact with the app are created as instances of the View class. In this article, we will take a deep dive into the View class in Android and explain in detail how to implement it using Kotlin.

1. Definition of Android View

A view is a single UI element that is displayed on the screen. Elements such as buttons, text, images, and lists all correspond to views. They serve to constitute the user interface of the application and convey information to the user.

2. Basic View Classes

Android provides various types of view classes, among which notable classes include the following:

  • TextView: A view that displays text. You can set various text styles and sizes.
  • EditText: A text field that allows the user to input text.
  • Button: A clickable button.
  • ImageView: A view that displays an image.
  • LinearLayout: A container that aligns other views either vertically or horizontally.

3. Creating Views

Let’s look at how to create a view in an Android app using Kotlin. Below is a basic example of view creation:


import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Create LinearLayout
        val layout = LinearLayout(this)
        layout.orientation = LinearLayout.VERTICAL

        // Create TextView
        val textView = TextView(this)
        textView.text = "Android View Class Example"
        textView.textSize = 24f

        // Create Button
        val button = Button(this)
        button.text = "Click Here"

        // Register button click listener
        button.setOnClickListener {
            textView.text = "Button has been clicked!"
        }

        // Add views to LinearLayout
        layout.addView(textView)
        layout.addView(button)

        // Set the Activity's content view
        setContentView(layout)
    }
}

4. Using Views in XML Layout

In Android, you can define layouts using XML files. After defining views in an XML file, you can reference these views in Kotlin. Below is an example of defining an XML layout:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android XML Layout Example"
        android:textSize="24sp"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Here"/>

</LinearLayout>

Now let’s look at how to access views using the XML layout from the Kotlin file:


import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private lateinit var button: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // Setting up the XML layout

        // Reference views from XML
        textView = findViewById(R.id.textView)
        button = findViewById(R.id.button)

        // Register button click listener
        button.setOnClickListener {
            textView.text = "Button has been clicked!"
        }
    }
}

5. Creating Custom Views

In Android, you can also create your own custom views in addition to the built-in views. Custom views are very useful for creating reusable UI elements that enhance code reusability.

Below is a simple example of how to create a custom view:


import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

class MyCustomView(context: Context, attrs: AttributeSet) : View(context, attrs) {
    private val paint = Paint()

    init {
        paint.color = Color.BLUE
        paint.style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // Draw a rectangle
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
    }
}

The above custom view is a simple example that draws a blue rectangle. This custom view can be utilized in an XML layout file:


<your.package.name.MyCustomView
    android:layout_width="match_parent"
    android:layout_height="200dp"/>

6. Changing View Properties

The properties of a view can be changed in various ways. Typically, you can either use XML layout properties or directly modify the view’s properties in code. For example, you can change the text color or size of a TextView.


textView.textSize = 20f
textView.setTextColor(Color.RED)

7. Understanding View Groups

A ViewGroup is a container that can hold multiple views. This enables the composition of complex UIs. Representative view groups include LinearLayout, RelativeLayout, and ConstraintLayout.

Below is an example using ConstraintLayout:


<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Confirm"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

8. Custom Attributes

You can also define custom attributes in custom views. This enables certain values to be set through XML attributes. Below is how to define custom attributes:


init {
    context.theme.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0).apply {
        try {
            // Reading custom attribute
            val customValue = getString(R.styleable.MyCustomView_customAttribute)
        } finally {
            recycle()
        }
    }
}

9. Lifecycle of Views

The view classes in Android have a lifecycle that is closely related to the lifecycle of Activities. The lifecycle of a view mainly aids in performing appropriate tasks in response to various state changes.

10. Handling View Events

All views can handle user input events. Let’s explore how to handle events like button clicks, text inputs, and touches. Below is an example of handling button click events:


button.setOnClickListener {
    // Code to execute when button is clicked
}

Conclusion

In this tutorial, we covered the basics to advanced concepts of the View class in Android app development. Views are core elements that make up the UI of Android, and understanding how to utilize them can lead to more effective and efficient Android application development.

Additional topics for further study include view animations, UI design patterns, and the MVVM architecture. I hope to explore these topics and gradually become a better Android developer!

kotlin android app development course, view events

Hello! In this course, we will take a detailed look at view event handling in Android app development. In app development, a view refers to all UI elements responsible for user interaction. It is important to effectively handle events that occur when users interact with the app, such as clicking a button or entering text. Kotlin provides various ways and tools to conveniently manage view events. In this course, we will cover a variety of topics, from basic click event handling to adding decorative animation effects and custom view events.

1. What are View Events?

View events refer to events that occur based on user input or interactions. The most commonly occurring view events in Android include touch, click, long press, drag, and swipe. These events trigger specific actions that occur when the user interacts with the app.

2. Basic Usage of Event Listeners

An event listener is an interface that defines methods to be called when a specific event occurs. Android provides various event listeners that can be written very concisely when used with Kotlin.

2.1 Button Click Event Handling

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

        val button = findViewById

The code above is a simple example that displays a Toast message when the button is clicked. The setOnClickListener method is used to set the click listener on the button, and the code to be executed upon click is defined using a lambda expression.

2.2 Handling Multiple View Events

Let’s explore how to handle events from multiple views. The code below is an example that handles various events occurring on a button and a text field.

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

        val button = findViewById

3. Handling Touch Events

In Android, various touch gestures can be recognized in addition to simple clicks. Here, we will introduce how to handle basic touch events.

3.1 Basic Structure of Touch Events

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

        val myView = findViewById(R.id.myView)
        myView.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    Toast.makeText(this, "Touch started", Toast.LENGTH_SHORT).show()
                    true
                }
                MotionEvent.ACTION_MOVE -> {
                    Toast.makeText(this, "Touch moved", Toast.LENGTH_SHORT).show()
                    true
                }
                MotionEvent.ACTION_UP -> {
                    Toast.makeText(this, "Touch ended", Toast.LENGTH_SHORT).show()
                    true
                }
                else -> false
            }
        }
    }
}

The code above uses touch events for a specific view to recognize the start, move, and end states while displaying appropriate messages. Each event can be distinguished through the MotionEvent object.

4. Using Gesture Detectors

A gesture detector is a way to manage various touch events more easily. The GestureDetector class can be used to recognize gestures such as swipes and double taps.

4.1 Setting Up the Gesture Detector

class MainActivity : AppCompatActivity() {
    private lateinit var gestureDetector: GestureDetector

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

        gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
            override fun onDoubleTap(e: MotionEvent?): Boolean {
                Toast.makeText(this@MainActivity, "Double tap detected", Toast.LENGTH_SHORT).show()
                return true
            }
            override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
                Toast.makeText(this@MainActivity, "Fling detected", Toast.LENGTH_SHORT).show()
                return true
            }
        })

        val myView = findViewById(R.id.myView)
        myView.setOnTouchListener { v, event ->
            gestureDetector.onTouchEvent(event)
            true
        }
    }
}

The gesture detector has the advantage of simplifying complex touch events into more concise code using GestureDetector.

5. Handling Custom View Events

Creating custom views and handling their events is also very important for enhancing the user experience of your app.

5.1 Creating a Custom View

class CustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private var paint = Paint()

    init {
        paint.color = Color.BLUE
        paint.style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                paint.color = Color.RED
                invalidate() // Redraw the view
                return true
            }
            MotionEvent.ACTION_UP -> {
                paint.color = Color.BLUE
                invalidate() // Redraw the view
                return true
            }
        }
        return super.onTouchEvent(event)
    }
}

The code above creates a custom view and handles touch events to change the color upon touch. The invalidate() method is used to redraw the view, updating the user interface.

6. Conclusion

In this course, we learned how to handle various view events in Android using Kotlin. We covered a wide range of topics, starting from basic click events, touch events, gesture detectors, to custom views. These techniques play a crucial role in enhancing app interactivity and improving user experience.

In the next course, we will explore how to use these view events to create more complex app interfaces and effectively combine them with animations. Enjoy the fun of Android app development and continue your journey as a developer!

Author: [Your Name]

Date: [Date]

course on Kotlin Android App Development, View Binding

When developing Android apps, the interaction between the layout (XML file) that composes the UI and the Kotlin code is very important. For a long time, the findViewById method was used to connect the XML files that structure the layout and Kotlin code, but this diminished code readability and posed a risk of errors. To solve these issues, a feature called View Binding has been introduced. In this tutorial, we will explain in detail the concept of view binding in Android app development using Kotlin, how to set it up, how to use it, and precautions to take.

1. What is View Binding?

View binding is a feature that allows you to directly reference views defined in the XML layout file from your code. By using view binding, there is no need to retrieve views through findViewById(), and you can easily reference views through the view binding class that is automatically generated when the application is compiled.

2. Advantages of View Binding

  • Type Safety: View binding connects views at compile time, reducing the occurrence of NullPointerException (NPE) issues that may arise at runtime.
  • Readability: Reducing the number of findViewById() calls makes the code cleaner and more readable.
  • Refactoring Support: When the view attribute names in the XML file are changed, the binding class is automatically updated, preventing potential errors in the code.

3. Preparing to Use View Binding

To use view binding, you must first enable it in the build.gradle file. Please refer to the steps below to set it up.

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

Unlike the previously used findViewById() method, view binding automatically generates a binding class for each view defined in the XML layout file. The name of the generated binding class is formed by converting the XML file name to CamelCase and adding the suffix ‘Binding’. For example, for the activity_main.xml file, a class named ActivityMainBinding is created.

4. Using View Binding

The process of using view binding is as follows.

4.1. Creating an XML Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, View Binding!" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me" />

</LinearLayout>

4.2. Using View Binding in an Activity

Here’s how to use view binding in an Activity. The example code below shows how to set up view binding and access views.

class MainActivity : AppCompatActivity() {

    // Declare the view binding object
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initialize the view binding object
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Set the button click listener
        binding.button.setOnClickListener {
            binding.textView.text = "Button Clicked!"
        }
    }
}

5. Using View Binding in a Fragment

View binding can also be used in Fragments. Here’s how to integrate the Fragment lifecycle with view binding.

class ExampleFragment : Fragment() {

    private var _binding: FragmentExampleBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentExampleBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Accessing views
        binding.exampleTextView.text = "Fragment View Binding Example"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null // Set the binding object to null to prevent memory leaks
    }
}

6. View Binding vs. Data Binding

View binding focuses on handling basic views, while data binding allows direct binding of data sources to UI components. To use data binding, the XML file needs to be modified as follows.

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="user"
            type="com.example.app.User" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.name}" />

    </LinearLayout>
</layout>

Data binding makes the coupling between the UI and data smoother and can automatically update the UI using observable data.

7. Precautions for View Binding

  • Preventing Leaks: When using view binding in a Fragment, make sure to set the binding object to null in the onDestroyView() method to avoid memory leaks.
  • Class Naming Rules: If the name of the XML file changes, the name of the automatically generated binding class will also change, so you should consider this when writing code.

Conclusion

In this tutorial, we covered the basic concepts of view binding, setup, usage, integration with Fragments, differences from data binding, and precautions. With view binding, you can manage and structure your Android app’s UI more easily and safely. Actively utilize view binding in your future app development to enhance readability and stability.

Wishing you luck on your Android app development journey!

course on Kotlin Android App Development, Variables and Functions

Using Kotlin for Android app development allows you to make the most of the language’s characteristics and advantages. This article will explain Kotlin’s variables and functions in detail. We will cover a variety of topics ranging from basic concepts to practical examples.

1. Concept of Variables

A variable is a named space that stores data. In Kotlin, declaring a variable is simple and intuitive. You can declare variables using the val and var keywords. val creates a read-only (immutable) variable, while var creates a mutable variable.

1.1. Immutable Variable (val)

An immutable variable cannot be changed once a value is assigned. Here is an example of declaring an immutable variable.

val pi: Double = 3.14159

In the above code, pi is an immutable variable, and once a value is assigned, it cannot be changed.

1.2. Mutable Variable (var)

A mutable variable can change its value as needed. Here is an example of declaring a mutable variable.

var count: Int = 0
count += 1

Here, the count variable is initialized to 0, and the value can be changed later.

1.3. Type Inference

In Kotlin, you can infer the type of a variable when initializing it without explicitly stating its type.

val message = "Hello, Kotlin!"

In the above code, the type of the message variable is automatically inferred as a string (String).

2. Concept of Functions

A function is a block of code that performs a specific task. In Kotlin, declaring a function is straightforward, and it also supports features like higher-order functions and lambda expressions.

2.1. Basic Function Declaration

The basic syntax for declaring a function is as follows.

fun functionName(parameter: Type): ReturnType {
    // function code
}

Below is an example of a function that adds two numbers.

fun add(a: Int, b: Int): Int {
    return a + b
}

This function takes two integers as parameters and returns their sum.

2.2. Parameters with Default Values

In Kotlin, you can set default values for function parameters. Parameters with default values can be omitted during the function call.

fun greet(name: String = "Guest") {
    println("Hello, $name!")
}

In the above example, if you omit the parameter when calling the greet function, “Guest” will be used as the default value.

2.3. Higher-Order Functions

Kotlin supports higher-order functions that can accept functions as parameters or return functions. Let’s look at the following example.

fun operation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

Here, the operation function takes two integers as input and accepts a function that performs a specific operation as a parameter.

3. Example Project: Simple Calculator App

Now let’s create a simple calculator app using the variables and functions we’ve learned above.

3.1. Project Setup

Create a new project in Android Studio. Set the app name to “SimpleCalculator” and choose the default Activity.

3.2. UI Design

In the activity_main.xml file, set up the UI as shown below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/input1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="First Number"
        android:inputType="numberDecimal"/>

    <EditText
        android:id="@+id/input2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Second Number"
        android:inputType="numberDecimal"/>

    <Button
        android:id="@+id/addButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add"/>

    <TextView
        android:id="@+id/resultView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result: "/>

</LinearLayout>

3.3. MainActivity.kt Code

Now let’s add the logic in the MainActivity.kt file.

package com.example.simplecalculator

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

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

        val input1 = findViewById<EditText>(R.id.input1)
        val input2 = findViewById<EditText>(R.id.input2)
        val addButton = findViewById<Button>(R.id.addButton)
        val resultView = findViewById<TextView>(R.id.resultView)

        addButton.setOnClickListener {
            val num1 = input1.text.toString().toDoubleOrNull() ?: 0.0
            val num2 = input2.text.toString().toDoubleOrNull() ?: 0.0
            val result = add(num1, num2)
            resultView.text = "Result: $result"
        }
    }

    private fun add(a: Double, b: Double): Double {
        return a + b
    }
}

4. Conclusion

In this article, we took a closer look at Kotlin’s variables and functions. You have learned how to store data using variables and how to reuse code with functions. Through the simple calculator app example above, I hope you have understood how variables are used in actual app development. We look forward to your continued development of various apps utilizing Kotlin!