
以前紹介した、
【はじめてのKotlinプログラミング(2)】15分で作る占いアプリ(AndroidStudio)
ですが、微妙に直したいコードがあるので、一応書き直したのを下記(ktの方)。
【ポイントは】
1)varをやっぱりvalにした
後々、書き方を基本に忠実に、「基本的にはval」(変更する値の時だけvar)に直したので、占いアプリもそうした。
2)「4-2)表示」のところで uranai.get(num) を、uranai[num] にした
配列の表示は 変数名[] とやるべき(変数名.get()は古い)ので、それを直した。
こんなところですかね。
書き直したコード
▼activity_main.xml(こっちは変更なし)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > < TextView android:id = "@+id/uranaiText" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_marginTop = "32dp" android:text = "今日の運勢" android:textSize = "30sp" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> < Button android:id = "@+id/uranaiBtn" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_marginTop = "32dp" android:text = "占う" app:layout_constraintEnd_toEndOf = "parent" app:layout_constraintStart_toStartOf = "parent" app:layout_constraintTop_toBottomOf = "@+id/uranaiText" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
▼MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package com.example.uranaiapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) //1)idを取得 val tv:TextView = findViewById(R.id.uranaiText) val btn:Button = findViewById(R.id.uranaiBtn) //2)クリック処理 btn.setOnClickListener { //4-1)配列で、文言を用意 val uranai = arrayOf( "大吉" , "中吉" , "小吉" , "凶" ) //tv.text = "大吉" //3)乱数を作ってみる val num = Random().nextInt(uranai.count()) //tv.text = num.toString() //4-2)表示 tv.text =uranai[num] } } } |