Android application development (supports both Java and Kotlin) How do you implement this? ~ Button edition ~

This article is the first of "Android application development: how do you implement this?"

The main target is (arbitrarily) assuming "beginners and intermediates who have learned to google" like me. Since it explains both Java and Kotlin, even those who say "I understand the implementation in Java, but how do you write it in Kotlin?" I think it will be useful.

A sample of this project can be found at the link below. The master branch is the Kotlin source code and the java branch is the Java source code.

https://github.com/Dai1678/SampleCodePrograms

Button implementation

I think it's the first thing that impresses me when I start developing Android apps.

As a sample

--The text changes when you press the Button --When you press the Floating Action Button, the Snack bar is displayed.

I tried to do that.

environment

Android Studio 3.0+ Confirmed operation on Android 8.0

Since we will use the Floating Action Button, add the following statement to your Gradle file.

build.gradle


apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "net.ddns.dai.samplecodeprograms"
        minSdkVersion 15
        targetSdkVersion 27
        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'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:27.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Operation demo

ButtonSampleActivity.gif

XML description

The way to write around FloatingActionButton is a little different depending on what the root tag is. Please see according to the layout of the application you are making.

--At LinearLayout

activity_button_sample.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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"
    android:orientation="vertical"
    tools:context="net.ddns.dai.samplecodeprograms.ButtonSampleActivity">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="About Button implementation" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:id="@+id/changeText"
                android:text="Please press"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:id="@+id/textChangeButton"
                android:text="Button"/>

         </LinearLayout>

         <android.support.design.widget.FloatingActionButton
             android:id="@+id/fab"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="bottom|end"
             android:layout_margin="@dimen/fab_margin"
             app:srcCompat="@android:drawable/btn_star" />

         <!-- @dimen/fab_margin -> 16dp -->

     </FrameLayout>

</LinearLayout>

The important part is that the content part is surrounded by FrameLayout. FrameLayout is used when you want to display View in an overlapping manner. Because there is a Floating Action Button. It's important to note that the components in this Layout cannot be positioned (all displayed in the upper left). Place the component by putting LinearLayout in this.

In this case, the position of the Floating Action Button can be specified by setting ʻandroid: layout_gravity = "bottom | end" `.

--At Relative Layout

You don't have to use FrameLayout because you can place them in relative positions. It's okay if you specify the position like ↓.

activity_button_sample.xml


<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

--At Coordinator Layout

As I will explain later, it is okay to think about FloatingActionButton in the same way as Relative Layout. If you select Basic Activity when creating a new Activity, this is used by default. If you want to use it even more coolly, maybe you should use this one?

Explanation of Activity

I think there are various ways to describe button processing. There are two ways I use it properly. I will briefly explain in Java and Kotlin with source code respectively.

Java edition

--When there is only one Button process (FloatingActionButton is omitted as an example)

ButtonSampleActivity.java


public class ButtonSampleActivity extends AppCompatActivity {

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

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        boolean flag = false;

        Button button = findViewById(R.id.textChangeButton);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                TextView textView = findViewById(R.id.changeText);

                if (flag){
                    textView.setText("Please press");
                    button.setText("BUTTON");
                    flag = false;

                }else{
                    textView.setText("Button was pressed!");
                    button.setText("return");
                    flag = true;
                }
             }
         });
    }
}

This is a method that is often introduced in sample code posted on many websites and Android Developers. I'm using an anonymous class inside the onCreate method. If you have one or two Buttons, you can do it this way.

--When there are multiple Button processes

ButtonSampleActivity.java


public class ButtonSampleActivity extends AppCompatActivity implements View.OnClickListener {

    Button button;
    boolean flag = false;

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

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        button = findViewById(R.id.textChangeButton);
        button.setOnClickListener(this);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){

            case R.id.textChangeButton:
                TextView textView = findViewById(R.id.changeText);

                if (flag){
                    textView.setText("Please press");
                    button.setText("BUTTON");
                    flag = false;

                }else{
                    textView.setText("Button was pressed!");
                    button.setText("return");
                    flag = true;
                }

                break;

            case R.id.fab:
                Snackbar.make(view, "fab has been pressed!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                break;
        }
    }
}

If you don't want to use anonymous classes, implement OnClickListener. First of all, please write in the first line. If you get an error with the red line, the red balloon will use the method publick void onClick (View view) {} on Android Studio. You will be asked to create it, so if you execute it, it will automatically create a method for you. (You can write it yourself)

In the onClick method, the id of the Button specified in xml is acquired by view.getId () and the processing is divided.

It's easy to forget about findViewById and setOnClickListener (this). Be careful! (It can be simplified by using Butter Knife or Data Biding, but I didn't want it to change significantly from the existing writing style. Not introduced. )

Kotlin edition

As it is written in build.gradle, here we have introduced kotlin-android-extensions. This is quite convenient, you can use the id name specified in xml as it is, and the amount of code can be very small.

--When there is only one Button process

ButtonSampleActivity.kt


class ButtonSampleActivity : AppCompatActivity() {

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

        val actionBar = supportActionBar
        actionBar!!.setDisplayHomeAsUpEnabled(true)

        var flag = false

        //kotlin-android-Thanks to extensions, you can specify by id of xml without writing a sentence of findViewById! !!
        textChangeButton.setOnClickListener { view ->
            flag = if (flag){
                    changeText.text = "Please press"
                    textChangeButton.text = "BUTTON"
                    false

                }else{
                    changeText.text = "Button was pressed"
                    textChangeButton.text = "return"
                    true
                }
        }

    }
}

It's much cleaner than the Java source code, isn't it? No findViewById, useless null checks, onClick, and no semicolons! Alright, let's get started with Kotlin now ()

--When there are multiple Button processes

ButtonSampleActivity.kt


class ButtonSampleActivity : AppCompatActivity(), View.OnClickListener {

    private var flag = false

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

        val actionBar = supportActionBar
        actionBar!!.setDisplayHomeAsUpEnabled(true)

        //kotlin-android-Thanks to extensions, you can specify by id of xml without writing a sentence of findViewById! !!
        textChangeButton.setOnClickListener(this)   
        fab.setOnClickListener(this)

    }

    override fun onClick(view: View) {

        when (view.id){     //Since there is no switch statement, use the when statement
            R.id.textChangeButton -> {
                this.flag = if (flag){
                    changeText.text = "Please press"
                    textChangeButton.text = "BUTTON"
                    false

                }else{
                    changeText.text = "Button was pressed"
                    textChangeButton.text = "return"
                    true
                }
            }

            R.id.fab -> {
                Snackbar.make(view, "fab has been pressed!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show()
            }
        }
    }
}

This is also a method of writing the onClick method outside the onCreate method. What I want to be aware of about this source code is that it differs from Java.

--Add with a comma instead of writing implements --Use the when statement because there is no switch statement in Kotlin --Type inference of var, val

What a place, such as.

reference

A detailed description of Kotlin's appeal and notation

-I received an order for Android development, so it was great to use Kotlin tightly

Next time preview

Write around text such as TextView and EditText.

Afterword

I would like to show it to juniors at the university, but I would be grateful if Qiita users could comment if there is demand. If you have any mistakes, please make a correction request.

Recommended Posts

Android application development (supports both Java and Kotlin) How do you implement this? ~ Button edition ~
Android application development (supports both Java and Kotlin) How do you implement this? ~ Text Edition ~
Summary of good points and precautions when converting Java Android application to Kotlin