0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

kotlinでAndroidアプリの画面遷移

Last updated at Posted at 2021-11-13

備忘録としてkotlinメモ

結論を言えば、Insertを使えば画面遷移が実現可能で、対象のコードだけで言えば以下2行です。

val intent = Intent(this,SecondActivity::class.java)
startActivity(intent)

ファイル作成の手順、マニフェストファイル メモ

まず画面を準備

画面1

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

        // viewの取得
        val btnStart :Button = findViewById(R.id.btnStart)

        // ボタン押下で次の画面へ
        btnStart.setOnClickListener {
            val intent = Intent(this,SecondActivity::class.java)
            startActivity(intent)
        }
    }
}


画面2

SecondActivity.kt
package com.example.sampleintent

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

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

        // View取得
        val btnBack : Button = findViewById(R.id.btn)

        // タップアクション
        btnBack.setOnClickListener {
            finish() // 元画面に戻る(画面のスタックしている状態を外すメソッド)
        }
    }
}

ファイルの作成方法は、Fileタブから生成

スクリーンショット 2021-11-14 1.15.18.png

上記方法で作成していれば自動生成されるので特に気にする必要はないのですが、リネームなどした場合には以下のようにAndroidManifest.xmlには手動で追加、修正する必要がある

<activity android:name=".画面のクラス名"></activity> <= これの追加が必要

以下実際のソース

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

    <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/Theme.SampleIntent">
        <activity android:name=".SecondActivity"> // 画面2のクラス
        </activity>
        <activity android:name=".MainActivity"> // 画面1のクラス
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

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

</manifest>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?