前提・実現したいこと
AndroidStudioでKotlinの勉強を始めたばかりの初心者です。
本を一冊買って、さあ、はじめようか、
というところなのですが。
本には
import kotlinx.android.synthetic.main.activity_main.*
をインポート
とだけ記述されているので、
よくわからないまま、ネットで調べて、そのままコピペしたところ
明らかにエラーっぽい感じで赤くなっています。
おそらくそれが原因だと思いますが
その下にコードを書いても
エラーっぽく赤くなっています。
該当のソースコード
kotlin
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener{ textView.text = "こんにちは" } } }
xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </androidx.constraintlayout.widget.ConstraintLayout>
試したこと
import kotlinx.android.synthetic.main.activity_main.*
をごっそり削除して
ネットで調べて見よう見まねで
var tv:TextView = findViewById(R.id.textView)
var btn:Button = findViewById(R.id.button)
btn.setOnClickListener{ tv.text = "こんにちは" }
これだと上手くいきました。
これはこれでいいとは思うのですが
テキストに記載されているコードとは違うので、どうも腑に落ちない。
補足情報(FW/ツールのバージョンなど)
AndroidStudio4.1.3
まだ回答がついていません
会員登録して回答してみよう