Android Studio Logo
Android Studio Logo

How to Create Your First Android App with Code: A Beginner’s Guide

As a content creator for carcodescanner.store and a car repair expert, I’m shifting gears to guide you through the exciting world of Android app development. You might be surprised how skills in diagnostics and problem-solving translate into coding! In this article, we’ll explore how to create your very first Android application, even if you’re a complete beginner. We’ll focus on using code to build your app, providing a hands-on approach to learning.

This guide is inspired by and expands upon existing resources to give you an even better learning experience. Let’s dive into the world of Android development and get coding!

I. Setting Up Your Development Environment

Before we write a single line of code, we need to set up our development environment. Think of this as preparing your garage before starting a car repair – having the right tools in place is crucial.

  1. Install Android Studio: If you haven’t already, download and install Android Studio. This is the official Integrated Development Environment (IDE) for Android app development, provided by Google. Make sure your computer meets the system requirements listed at the bottom of the download page. For a more detailed walkthrough of the setup process, you can refer to this installation guide.

    Android Studio provides all the tools necessary to design, code, test, and debug your Android applications. It includes a code editor, compiler, debugger, and emulators to run your apps.

    Tip: Keep Android Studio updated to the latest version to benefit from new features, bug fixes, and performance improvements.

  2. Create a New Project: Once Android Studio is installed and running, you’ll be greeted with the “Welcome to Android Studio” dialog. Click on New Project to start creating your first app.

    This will open the New Project wizard, where you can choose a template for your project. Templates are pre-configured project setups that provide a starting point for different types of applications.

  3. Select “Empty Compose Activity” Template: In the New Project window, make sure the Phone and Tablet tab is selected. Then, choose the Empty Compose Activity template. This template is perfect for beginners as it provides a minimal project structure using Jetpack Compose, a modern UI toolkit for Android.

    Why “Empty Compose Activity”? This template utilizes Jetpack Compose, Google’s recommended modern toolkit for building native Android UIs. Compose simplifies UI development with declarative Kotlin code.

  4. Configure Your Project: Click Next to configure your project details. You’ll see several fields to fill in:

    • Name: Give your project a name. For this tutorial, let’s call it “Greeting Card App.” This is the name of your application.
    • Package name: Leave this as it is for now. It’s a unique identifier for your app in the Android system and Google Play Store. The default is usually com.example.greetingcard.
    • Save location: Note down the save location. This is where all your project files will be stored on your computer.
    • Language: Ensure Kotlin is selected. Jetpack Compose is primarily designed for use with Kotlin.
    • Minimum SDK: Choose API 21: Android 5.0 (Lollipop). This specifies the minimum Android version your app will run on. Choosing a lower API level increases the compatibility of your app with older devices.
    • Use legacy android.support libraries: Make sure this box is unchecked.

  5. Finish Project Creation: Click Finish. Android Studio will now set up your project. This might take a few moments as it downloads dependencies and configures the project structure. You’ll see a progress bar and messages indicating the setup process.

    Alt Text: Progress indicator in Android Studio showing the project setup and build process.

    Once the project is set up, Android Studio might display a “What’s New” panel. You can close this for now.

  6. Explore Android Studio Interface: Take a moment to familiarize yourself with the Android Studio interface. Click Split at the top right of Android Studio to view both the code and design previews simultaneously.

    You’ll notice three main areas:

    • Project View (1): This panel displays the file and folder structure of your project. It helps you navigate through your project files.
    • Code View (2): This is where you write and edit your code. It’s the central area for coding your app’s logic and UI.
    • Design View (3): This panel provides a preview of your app’s user interface. It shows how your UI will look on an Android device or emulator. Initially, you might see a blank panel with a message.
  7. Build and Refresh Preview: In the Design view, click Build & Refresh. This will compile your project and update the preview panel. After the build process completes, you should see a preview displaying the text “Hello Android!“.

    The “Empty Compose Activity” template comes with pre-written code that displays this default text. You’ve just built and previewed your first Android app!

II. Navigating Your Project Files

Understanding the project structure is essential for efficient Android development. Let’s explore the key files in your project.

  1. Project Tab: Locate the Project tab in Android Studio (usually on the left side). This tab provides a structured view of your project files. By default, it might be set to the Android view.

    The Android view is a simplified and organized view of your project structure, focusing on the key files you’ll typically work with during Android development.

  2. Android View vs. Project Source Files View: Android Studio offers different ways to view your project files. The Android view is great for development, but sometimes you might need to see the actual file system structure.

    To see the underlying file structure, change the dropdown menu in the Project tab from Android to Project Source Files.

    The Project Source Files view shows the directory structure as it is on your computer. For most Android development tasks, the Android view is more convenient. Switch back to the Android view for the rest of this tutorial.

  3. Package Name: In the Android view, you’ll see your package name, which you configured during project setup (e.g., com.example.greetingcard). Packages are essentially folders that organize your code files.

    Your Kotlin code files for this app will be located within this package.

III. Customizing Your App’s Text

Let’s personalize your app by changing the default “Hello Android!” text. We’ll work with the MainActivity.kt file, which contains the code for your app’s main screen.

  1. Open MainActivity.kt: In the Project view, navigate to your package name (e.g., com.example.greetingcard) and open the MainActivity.kt file. This file contains the Kotlin code that defines the behavior and UI of your app.

    You’ll see code that looks similar to this:

    class MainActivity : ComponentActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                GreetingCardTheme {
                    // A surface container using the 'background' color from the theme
                    Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
                        Greeting("Android")
                    }
                }
            }
        }
    }
    
    @Composable
    fun Greeting(name: String) {
        Text(text = "Hello $name!")
    }
    
    @Preview(showBackground = true)
    @Composable
    fun DefaultPreview() {
        GreetingCardTheme {
            Greeting("Android")
        }
    }
  2. onCreate() Function: The onCreate() function is the entry point of your app’s activity. It’s called when your app starts. Inside onCreate(), the setContent() function is used to define the UI using composable functions.

  3. Greeting() Composable Function: Look at the Greeting() function, marked with the @Composable annotation. This is a composable function, responsible for creating a part of your UI. In this case, it displays a Text composable.

    @Composable
    fun Greeting(name: String) {
        Text(text = "Hello $name!")
    }

    Composable functions are the building blocks of Jetpack Compose UI. They are functions that describe the UI elements and how they should be displayed.

  4. Modify Greeting() Function: Let’s change the greeting message to introduce yourself. Modify the Greeting() function like this:

    @Composable
    fun Greeting(name: String) {
        Text(text = "Hi, my name is $name!")
    }

    We’ve changed the text within the Text composable to “Hi, my name is $name!”. The $name is a placeholder that will be replaced by the value passed to the name parameter of the Greeting() function.

  5. Update DefaultPreview() Function: The DefaultPreview() function, annotated with @Preview, is used to display a preview of your UI in the Design view. Let’s update it to use your name.

    @Preview(showBackground = true)
    @Composable
    fun DefaultPreview() {
        GreetingCardTheme {
            Greeting("YourName") // Replace "YourName" with your actual name
        }
    }

    Replace "YourName" with your actual name.

  6. Build & Refresh Preview: Click Build & Refresh in the Design view. You should now see the preview updated with your personalized greeting!

    Congratulations! You’ve successfully modified the text in your Android app using code.

IV. Changing the Background Color

Let’s make our greeting card more visually appealing by adding a background color. We’ll use the Surface composable to achieve this.

  1. Wrap Text with Surface: To add a background color, we need to wrap our Text composable within a Surface composable. Surface is a container that can have its appearance modified, including its background color.

    Select the Text composable line in the Greeting() function, press Alt+Enter (Windows) or Option+Enter (Mac), and choose Surround with widget.

  2. Select “Surround with Container”: In the “Surround with” menu, choose Surround with Container.

    By default, it might suggest a Box container. We’ll replace Box with Surface.

  3. Replace Box with Surface: Delete Box and type Surface() instead. Your Greeting() function should now look like this:

    @Composable
    fun Greeting(name: String) {
        Surface() {
            Text(text = "Hi, my name is $name!")
        }
    }
  4. Add color Parameter to Surface: The Surface composable has a color parameter that we can use to set the background color. Add the color parameter and set it to Color.

    @Composable
    fun Greeting(name: String) {
        Surface(color = Color) {
            Text(text = "Hi, my name is $name!")
        }
    }
  5. Import Color: You might see Color underlined in red, indicating an unresolved reference. To fix this, you need to import the Color class. Scroll to the top of the MainActivity.kt file where the import statements are and add the following import:

    import androidx.compose.ui.graphics.Color

    Your import section should now include:

    import android.os.Bundle
    import androidx.activity.ComponentActivity
    import androidx.activity.compose.setContent
    import androidx.compose.foundation.layout.fillMaxSize
    import androidx.compose.material.MaterialTheme
    import androidx.compose.material.Surface
    import androidx.compose.material.Text
    import androidx.compose.runtime.Composable
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.tooling.preview.Preview
    import com.example.greetingcard.ui.theme.GreetingCardTheme
    import androidx.compose.ui.graphics.Color // Added import
  6. Optimize Imports (Optional but Recommended): To keep your imports organized, you can use Android Studio’s “Optimize Imports” feature. Go to Help in the top toolbar, type Optimize Imports, and click Optimize Imports. This will automatically sort your imports alphabetically and remove any unused imports.

  7. Choose a Color: Now, go back to the Surface composable in your Greeting() function. After Color, add a dot (.) to see a list of available colors. Android Studio’s code completion will suggest various color options.

  8. Select a Color (e.g., Magenta): Choose a color you like. For example, let’s use Color.Magenta.

    @Composable
    fun Greeting(name: String) {
        Surface(color = Color.Magenta) {
            Text(text = "Hi, my name is $name!")
        }
    }
  9. Build & Refresh Preview: Click Build & Refresh. You should now see your text with a magenta background!

V. Adding Padding

Currently, the text is right up against the edges of the magenta background. Let’s add some padding to create space around the text.

  1. Import padding and dp: We’ll use the Modifier.padding() modifier to add padding. First, add these imports to your import statements at the top of MainActivity.kt:

    import androidx.compose.ui.unit.dp
    import androidx.compose.foundation.layout.padding

    Remember to use “Optimize Imports” to keep your imports organized.

  2. Apply padding Modifier to Text: Add the modifier parameter to the Text composable and use Modifier.padding(24.dp) to add 24dp (density-independent pixels) of padding around the text.

    @Composable
    fun Greeting(name: String) {
        Surface(color = Color.Magenta) {
            Text(text = "Hi, my name is $name!", modifier = Modifier.padding(24.dp))
        }
    }

    Modifiers are used in Jetpack Compose to augment or decorate composable functions. Modifier.padding() adds space around the element it’s applied to.

  3. Build & Refresh Preview: Click Build & Refresh. You’ll now see padding around your text, making it look much better!

    Excellent! You’ve built your first Android app with Jetpack Compose and learned how to customize text, background color, and padding.

VI. Reviewing the Code

Here’s the complete code for your MainActivity.kt file:

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.greetingcard.ui.theme.GreetingCardTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            GreetingCardTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Greeting("Android")
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Surface(color = Color.Magenta) {
        Text(text = "Hi, my name is $name!", modifier = Modifier.padding(24.dp))
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    GreetingCardTheme {
        Greeting("YourName") // Replace "YourName" with your actual name in preview
    }
}

VII. Conclusion

You’ve taken your first steps into Android app development and successfully created a simple greeting card app! This is a significant accomplishment. You’ve learned how to:

  • Set up Android Studio and create a new project.
  • Navigate project files.
  • Modify text content in your app.
  • Change background colors using Surface.
  • Add padding to UI elements using Modifier.
  • Preview your app’s UI in Android Studio.

This tutorial is just the beginning. To further your learning, explore running your app on an emulator or a physical Android device. You can also delve deeper into Jetpack Compose and learn about more UI elements, layouts, and interactions.

Summary of Key Learnings

  • Creating a New Project: Start Android Studio, click New Project > Empty Compose Activity > Next, configure project settings, and click Finish.
  • Previewing Your App: Use the Design view and Build & Refresh to see a preview of your UI.
  • Composable Functions: Functions annotated with @Composable are used to build UI in Jetpack Compose. They are capitalized, annotated with @Composable, and do not return values.
  • Modifiers: Modifiers are used to decorate or augment composable functions, such as adding padding or changing layout behavior.

Next Steps

To continue your Android development journey, consider these next steps:

  • Run your app on an emulator or device: Learn how to run your newly created app on an Android emulator or a physical Android device for real-world testing.
  • Explore more Compose basics: Dive deeper into Jetpack Compose fundamentals, including layouts, state management, and handling user interactions.
  • Follow the complete Android Basics with Compose course: This tutorial is part of a larger Android Basics with Compose course. Continue with the next codelab in the pathway to expand your knowledge.

Keep coding and exploring – the world of Android development is vast and exciting!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *