0
0

Android複数画面で変数の共有

Posted at
  • AndroidManifest.xml
  • MyApplication.kt
  • FirstActivity.kt
  • SecondActivity.kt

AndroidManifest.xmlの編集

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplicationTest1"
        android:name=".MyApplication"#これを追加
        tools:targetApi="31"
        >
        <activity
            android:name=".HomeActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyApplicationTest1">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 他のアクティビティ -->
        <activity android:name=".MainActivity" />
        <!-- 他のアクティビティはここに追加 -->

    </application>

</manifest>

MyApplication.kt

package com.example.myapplicationtest1

import android.app.Application

class MyApplication : Application() {
    // 共通変数の定義
    var targetCd: String = ""

    override fun onCreate() {
        super.onCreate()
        // アプリケーション全体で共有するリソースや設定をここで初期化します
        // 例: アプリ全体で使う設定やシングルトンの初期化
    }
}

FirstActivity.kt

package com.example.myapplicationtest1

import android.os.Bundle
import android.widget.Button
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import android.widget.EditText
import android.app.AlertDialog
import android.app.Application
import android.content.Intent
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.ViewModelProvider

class FirstActivity : ComponentActivity() {

    // グローバル変数として Button を宣言
    private lateinit var button: Button
    private lateinit var input: EditText
    // カスタムApplicationクラスから共通変数にアクセス
    private lateinit var app: MyApplication

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

        // Use XML layout このXMLをデザインとして使用します。
        setContentView(R.layout.home)

        button = findViewById(R.id.buttonTargetConfirm)
        input =  findViewById(R.id.targetCd)

        // Input項目へフォーカスを当てる
        input.requestFocus()

        /**
        *ここが重要
        */
        app = application as MyApplication

        // buttonクリック時のイベント
        button.setOnClickListener{
            buttonClickEvent()
        }
    }

    /**
     * CHECKボタンクリック時イベント
     */
    private fun buttonClickEvent(){
        val a = input.text.toString()
        if(a == ""){
            showMessageDialog("対象コードをが未入力です")
        }else{
            app.targetCd = a
            //別画面へ遷移
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
    }



}

SecondActivity.kt

class MainActivity : ComponentActivity() {

    // Define Global var
    private lateinit var label: TextView
    private lateinit var input: EditText
    private lateinit var button: Button
    // カスタムApplicationクラスから共通変数にアクセス
    private lateinit var app: MyApplication

    // MyVariable
    private val array = arrayListOf<String>()

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

        // Use XML layout このXMLをデザインとして使用します。
        setContentView(R.layout.layout)

        // カスタムApplicationクラスの取得
        app = application as MyApplication

        // Access Items
        label = findViewById(R.id.label)
        input = findViewById(R.id.input)
        button = findViewById(R.id.btn)

        // Define variables
        val labelText = app.targetCd   //ここで値の取得
        val inputHint = "ReadBarcode"

        // Set variables to the views
        label.text = labelText
        input.hint = inputHint


        // buttonクリック時のイベント
        button.setOnClickListener{
            buttonClickEvent()
        }

    }

    /**
     * CHECKボタンクリック時イベント
     */
    private fun buttonClickEvent(){
        val tempinput: String = input.text.toString()
        if(tempinput != "") {
            //inputに入力されている文字を配列に追加
            array.add(input.text.toString())

            // TableLayoutの参照を取得
            val tableLayout: TableLayout = findViewById(R.id.table)
            // データを全削除
            tableLayout.removeAllViews()
            // データ行を追加
            for (dataRow in array) {
                // TableRowを作成
                val tableRow = TableRow(this)
                val textView = TextView(this)
                textView.text = dataRow
                textView.setPadding(8, 8, 8, 8)
                tableRow.addView(textView)


                // TableRowをTableLayoutに追加
                tableLayout.addView(tableRow)
            }

            //空文字の設定
            input.setText(getString(R.string.empty_string))
        }
    }




}



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