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

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

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

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

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

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

Q&A

解決済

1回答

1663閲覧

画面遷移が何故かできません

eotw

総合スコア48

Android

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

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

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

0グッド

0クリップ

投稿2022/05/06 06:05

実現したいこと

クリックハンドラーで画面遷移をさせたい
・ボタンタップ→画面遷移
・MainActivity→AddActivityに遷移

発生している問題・エラーメッセージ

特にエラーコードは発生しておらず、ボタンをタップしても何も起こりません。
必要な記述は試しましたが、何が原因で動かないのか分からないので、教えて頂きたいです。

試したこと

・MainActivityにsetOnClickListenerを実装、Intentで画面遷移
・AndroidManifestにactivityの追加

該当のソースコード

▼MainActivity

Kotlin

1package com.example.showtextonmapapp 2 3import省略 4 5class MainActivity : AppCompatActivity(), OnMapReadyCallback { 6 7 private lateinit var mMap: GoogleMap 8 private val MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 1 9 private lateinit var fusedLocationProviderClient : FusedLocationProviderClient 10 private lateinit var lastLocation: Location 11 private var locationCallback : LocationCallback? = null 12 private lateinit var realm: Realm 13 14 override fun onCreate(savedInstanceState: Bundle?) { 15 super.onCreate(savedInstanceState) 16 setContentView(R.layout.activity_main) 17 18 //画面をスリープにしない 19 window.addFlags(FLAG_KEEP_SCREEN_ON) 20 21 // Obtain the SupportMapFragment and get notified when the map is ready to be used. 22 val mapFragment = supportFragmentManager 23 .findFragmentById(R.id.map) as SupportMapFragment 24 mapFragment.getMapAsync(this) 25 fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this) 26 27 realm = Realm.getDefaultInstance() 28 val toAddBtn: Button = findViewById(R.id.toAddBtn) 29 toAddBtn.setOnClickListener { 30 val intent = Intent(this, AddActivity::class.java) 31 intent.putExtra("lat", lastLocation.latitude) 32 intent.putExtra("lng", lastLocation.longitude) 33 startActivity(intent) 34 } 35 } 36 37 override fun onMapReady(googleMap: GoogleMap) { 38 mMap = googleMap 39 40 checkPermission() 41 } 42 43 private fun checkPermission() { 44 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 45 myLocationEnable() 46 } else { 47 requestLocationPermission() 48 } 49 } 50 51 private fun requestLocationPermission() { 52 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { 53 //許可が拒否された場合 54 ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION) 55 } else { 56 //許可も求めていない場合 57 ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION) 58 } 59 } 60 61 override fun onRequestPermissionsResult( 62 requestCode: Int, 63 permissions: Array<out String>, 64 grantResults: IntArray 65 ) { 66 super.onRequestPermissionsResult(requestCode, permissions, grantResults) 67 when(requestCode) { 68 MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION->{ 69 if (permissions.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 70 //許可された 71 myLocationEnable() 72 } else { 73 showToast("現在位置は表示できません") 74 } 75 } 76 } 77 } 78 79 private fun myLocationEnable() { 80 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 81 mMap.isMyLocationEnabled = true 82 val locationRequest = LocationRequest().apply { 83 interval = 10000 84 fastestInterval = 5000 85 priority = LocationRequest.PRIORITY_HIGH_ACCURACY 86 } 87 locationCallback = object : LocationCallback() { 88 override fun onLocationResult(locationResult: LocationResult?) { 89 val textView : TextView = findViewById(R.id.textView) 90 if (locationResult?.lastLocation != null) { 91 lastLocation = locationResult.lastLocation 92 val currentLatLng = LatLng(lastLocation.latitude, lastLocation.longitude) 93 mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLatLng)) 94 textView.text = "Lat:${lastLocation.latitude}, Lng:${lastLocation.longitude}" 95 } 96 } 97 } 98 fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null) 99 } 100 } 101 102 private fun showToast(msg: String) { 103 val toast = Toast.makeText(this, msg, Toast.LENGTH_LONG) 104 toast.show() 105 } 106 107 override fun onPause() { 108 super.onPause() 109 if (locationCallback != null) { 110 fusedLocationProviderClient.removeLocationUpdates(locationCallback) 111 } 112 } 113 114 override fun onDestroy() { 115 super.onDestroy() 116 realm.close() 117 } 118 119}

▼AddActivity.kt

Kotlin

1package com.example.showtextonmapapp 2 3import androidx.appcompat.app.AppCompatActivity 4import android.os.Bundle 5import android.widget.Button 6import android.widget.EditText 7import android.widget.Toast 8import io.realm.Realm 9import io.realm.kotlin.createObject 10import io.realm.kotlin.where 11import java.util.* 12 13class AddActivity : AppCompatActivity() { 14 private lateinit var realm: Realm 15 16 override fun onCreate(savedInstanceState: Bundle?) { 17 super.onCreate(savedInstanceState) 18 setContentView(R.layout.activity_add) 19 realm = Realm.getDefaultInstance() 20 21 val lat = intent.getDoubleExtra("lat", 0.0) 22 val lng = intent.getDoubleExtra("lng", 0.0) 23 val saveBtn: Button = findViewById(R.id.saveBtn) 24 val cancelBtn: Button = findViewById(R.id.cancelBtn) 25 26 saveBtn.setOnClickListener { 27 val editText: EditText = findViewById(R.id.editText) 28 val shopInfoStr = editText.text?.toString() ?: "" 29 realm.executeTransaction { 30 val maxId = realm.where<ShopInfo>().max("id") 31 val nextId = (maxId?.toLong() ?: 0L) + 1L 32 val shopInfo = realm.createObject<ShopInfo>(nextId) 33 shopInfo.dateTime = Date() 34 shopInfo.lat = lat 35 shopInfo.lng = lng 36 shopInfo.shopInfo = shopInfoStr 37 } 38 showToast("保存しました") 39 finish() 40 } 41 cancelBtn.setOnClickListener {} 42 finish() 43 } 44 45 override fun onDestroy() { 46 super.onDestroy() 47 realm.close() 48 } 49 50 private fun showToast(msg: String) { 51 val toast = Toast.makeText(this, msg, Toast.LENGTH_LONG) 52 toast.show() 53 } 54}

▼activity_add.xml

Kotlin

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".AddActivity"> 8 9 <EditText 10 android:id="@+id/editText" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:layout_marginStart="100dp" 14 android:layout_marginTop="150dp" 15 android:layout_marginEnd="100dp" 16 android:ems="10" 17 android:inputType="textPersonName" 18 android:text="" 19 app:layout_constraintEnd_toEndOf="parent" 20 app:layout_constraintHorizontal_bias="0.497" 21 app:layout_constraintStart_toStartOf="parent" 22 app:layout_constraintTop_toTopOf="parent" /> 23 24 <Button 25 android:id="@+id/saveBtn" 26 android:layout_width="wrap_content" 27 android:layout_height="wrap_content" 28 android:layout_marginStart="100dp" 29 android:layout_marginTop="250dp" 30 android:text="保存" 31 app:layout_constraintStart_toStartOf="parent" 32 app:layout_constraintTop_toTopOf="parent" /> 33 34 <Button 35 android:id="@+id/cancelBtn" 36 android:layout_width="wrap_content" 37 android:layout_height="wrap_content" 38 android:layout_marginTop="250dp" 39 android:layout_marginEnd="100dp" 40 android:text="キャンセル" 41 app:layout_constraintEnd_toEndOf="parent" 42 app:layout_constraintTop_toTopOf="parent" /> 43 44 <TextView 45 android:id="@+id/textView3" 46 android:layout_width="wrap_content" 47 android:layout_height="wrap_content" 48 android:layout_marginTop="100dp" 49 android:text="テキストを入力してください" 50 app:layout_constraintEnd_toEndOf="parent" 51 app:layout_constraintStart_toStartOf="parent" 52 app:layout_constraintTop_toTopOf="parent" /> 53</androidx.constraintlayout.widget.ConstraintLayout>

▼AndroidManifest.xml

Kotlin

1<?xml version="1.0" encoding="utf-8"?> 2<manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.showtextonmapapp"> 4 5 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 6 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 7 8 <application 9 android:name=".CustomApplication" 10 android:allowBackup="true" 11 android:icon="@mipmap/ic_launcher" 12 android:label="@string/app_name" 13 android:roundIcon="@mipmap/ic_launcher_round" 14 android:supportsRtl="true" 15 android:theme="@style/Theme.ShowTextOnMapApp"> 16 <meta-data 17 android:name="com.google.android.geo.API_KEY" 18 android:value="@string/google_maps_key" /> 19 <activity 20 android:name=".MainActivity" 21 android:exported="true"> 22 <intent-filter> 23 <action android:name="android.intent.action.MAIN" /> 24 25 <category android:name="android.intent.category.LAUNCHER" /> 26 </intent-filter> 27 </activity> 28 <activity android:name=".AddActivity" /> 29 </application> 30 31</manifest>

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

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

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

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

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

hoshi-takanori

2022/05/06 06:18

AddActivity の onCreate の最後で finish してるからでは。finish はそのアクティビティを終了するメソッドです。
eotw

2022/05/06 06:29

それでした。。! setOnClickListenerのスコープから外れていました。。 ありがとうございます!
guest

回答1

0

自己解決

finish()をスコープ外に書いてしまっていました。

投稿2022/05/06 06:31

eotw

総合スコア48

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問