質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

Q&A

1回答

784閲覧

遷移先ViewListで選ばれた値を、遷移元のActivityで表示する方法

tomaa

総合スコア84

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

0グッド

0クリップ

投稿2020/09/24 05:24

編集2020/09/24 11:34

前提・実現したいこと

android-studioとKotlinを利用して、アプリを開発しています。

このアプリは、

  • ①:各Activityで共有する値を持つViewModelのクラス
  • ②:ListViewを持つActivity
  • ③:②のListViewで選ばれたアイテムを元に値を表示するActivity

で、構成されています。

下記に紹介しているコードの場合、ListViewで選ばれたアイテムに応じて、ViewModelの値は変化している事を確認できますが、ViewModelの値を表示するActivity(③)での表示の際に反映されません。

どのようにすれば、ViewModelの値に応じた表示を行えるでしょうか?

該当のソースコード

追記ViewModelにLiveDataを使用するように、AppState.kt,MainActivity.kt,ListActivity.ktを変更

build.gradle

gradle

1apply plugin: 'kotlin-android' 2 3apply plugin: 'kotlin-android-extensions' 4 5android { 6 compileSdkVersion 28 7 defaultConfig { 8 applicationId "com.sample.arrayvaluetest" 9 minSdkVersion 16 10 targetSdkVersion 28 11 versionCode 1 12 versionName "1.0" 13 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 } 15 buildTypes { 16 release { 17 minifyEnabled false 18 proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 19 } 20 } 21} 22 23dependencies { 24 implementation fileTree(dir: 'libs', include: ['*.jar']) 25 implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 26 implementation 'androidx.appcompat:appcompat:1.0.0-beta01' 27 implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 28 implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01' 29 implementation 'androidx.recyclerview:recyclerview:1.0.0-beta01' 30 testImplementation 'junit:junit:4.12' 31 androidTestImplementation 'androidx.test:runner:1.1.0-alpha4' 32 androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4' 33 34 implementation "com.google.android.material:material:1.1.0-alpha06" 35 36 def nav_version = '2.0.0' 37 implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" 38 implementation "androidx.navigation:navigation-ui-ktx:$nav_version" 39 40 implementation "androidx.fragment:fragment-ktx:1.3.0-alpha04" 41 42}

AppState.kt

kotlin

1package com.tomato_love.arrayvaluetest 2 3import androidx.lifecycle.MutableLiveData 4import androidx.lifecycle.ViewModel 5 6 7class AppState: ViewModel() { 8 9 var array = arrayOf("one","two","three") 10// var arrayIndex:Int = 0 11 var arrayIndex: MutableLiveData<Int> = MutableLiveData(0) 12 13}

MainActivity.kt

kotlin

1package com.tomato_love.arrayvaluetest 2 3import android.content.Intent 4import androidx.appcompat.app.AppCompatActivity 5import android.os.Bundle 6import android.widget.Button 7import android.widget.TextView 8import androidx.lifecycle.LifecycleOwner 9import androidx.lifecycle.Observer 10import androidx.lifecycle.ViewModelProvider 11 12 13class MainActivity : AppCompatActivity() { 14 15 lateinit var appState: AppState 16 17 override fun onCreate(savedInstanceState: Bundle?) { 18 19 appState = ViewModelProvider(this).get(AppState::class.java) 20 21 super.onCreate(savedInstanceState) 22 setContentView(R.layout.activity_main) 23 24 val text = findViewById<TextView>(R.id.text) 25 val button = findViewById<Button>(R.id.button) 26 27// text.text = appState.array[appState.arrayIndex] 28 29 appState.arrayIndex.observe({ lifecycle }, { 30 text.text = appState.array[it] }) 31 32 button.setOnClickListener { 33 val intent = Intent(this, ListActivity::class.java) 34 startActivity(intent) 35 } 36 37 } 38} 39 40

activity_main.xml

xml

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 xmlns:app="http://schemas.android.com/apk/res-auto" 6 android:layout_width="match_parent" 7 android:layout_height="match_parent" 8 tools:context=".MainActivity"> 9 10 <TextView 11 android:id="@+id/text" 12 android:text="initial text" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 app:layout_constraintBottom_toBottomOf="parent" 16 app:layout_constraintLeft_toLeftOf="parent" 17 app:layout_constraintRight_toRightOf="parent" 18 app:layout_constraintTop_toTopOf="parent"/> 19 20 <Button 21 android:id="@+id/button" 22 android:layout_width="wrap_content" 23 android:layout_height="wrap_content" 24 android:text="to list" 25 android:layout_marginTop="32dp" 26 app:layout_constraintTop_toBottomOf="@+id/text" 27 app:layout_constraintStart_toStartOf="parent" 28 app:layout_constraintEnd_toEndOf="parent" 29 /> 30 31</androidx.constraintlayout.widget.ConstraintLayout> 32

ListActivity.kt

kotlin

1package com.tomato_love.arrayvaluetest 2 3import android.os.Bundle 4import android.widget.ArrayAdapter 5import android.widget.ListView 6import android.widget.TextView 7import androidx.appcompat.app.AppCompatActivity 8import androidx.lifecycle.ViewModelProvider 9 10class ListActivity : AppCompatActivity() { 11 12 lateinit var appState: AppState 13 14 override fun onCreate(savedInstanceState: Bundle?) { 15 16 appState = ViewModelProvider(this).get(AppState::class.java) 17 18 super.onCreate(savedInstanceState) 19 setContentView(R.layout.activity_list) 20 21 val listView = findViewById<ListView>(R.id.listView) 22 23 val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, appState.array) 24 25 listView.adapter = adapter 26 27 listView.setOnItemClickListener { parent, view, position, id -> 28 val item = (view.findViewById<TextView>(android.R.id.text1)).text 29 30 when (item) { 31// "one" -> appState.arrayIndex = 0 32// "two" -> appState.arrayIndex = 1 33// "three" -> appState.arrayIndex = 2 34 35 "one" -> appState.arrayIndex.postValue(0) 36 "two" -> appState.arrayIndex.postValue(1) 37 "three" -> appState.arrayIndex.postValue(2) 38 } 39 println(appState.arrayIndex) 40 41 finish() 42 } 43 } 44} 45 46

activity_list.xml

kotlin

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 xmlns:app="http://schemas.android.com/apk/res-auto" 6 android:layout_width="match_parent" 7 android:layout_height="match_parent" 8 tools:context=".ListActivity"> 9 10 <ListView 11 android:id="@+id/listView" 12 android:layout_width="match_parent" 13 android:layout_height="match_parent"/> 14 15</androidx.constraintlayout.widget.ConstraintLayout> 16

補足情報(FW/ツールのバージョンなど)

Android Studio: 3.3.2

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

以下の方法で実装ができるかと思います。

  1. ListViewActivityから戻ってきたことを検知してsetする処理を作成する。
  2. もしくはViewModelの値をMainActivity側で監視する必要があります。

2の条件は学習コストがかかるのと処理が複雑になるため、オススメは1となります。
こちらに関しては startActivityForResultonActivityResult で実装可能です。
以下のURLが参考になります。

https://fernweh.jp/b/startactivityforresult/

やることとしてはstartActivitystartActivityForResultに変更、finish()前にsetResultを使用。
MainActivity側でonActivityResultを使って、戻ってきたことを検知して、textの値を変更してあげる形になります。

1をお試しになりたい場合は、ViewModelにLiveDataを持たせることで実装できるかと思います。 以下をご参考ください。
https://developer.android.com/topic/libraries/architecture/livedata?hl=ja

投稿2020/09/24 08:34

pg0084

総合スコア100

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tomaa

2020/09/24 11:32

ご回答いただきありがとうございます。 ご丁寧に解説していただきありがとうございます。 ご紹介していただいた1番目の方法(ListViewActivityから戻ってきたことを検知してsetする処理を作成する。)を試すため、追記をして載せたコードに変更しました。 しかし、以前選択した内容が反映されない状況です。 編集したコードに不備がありますでしょうか?
pg0084

2020/09/25 16:05

返信遅れました。 試していただきたいこととして、ListActivityで選択した際にObserveの中が呼ばれているか、値が変わっているか、また、postValueではなく、.setValueに変更する。 こちらご確認ください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問