我有一個帶有 3 個按鈕的活動,我希望每個按鈕都指向其他活動。我用 KOTLIN 編碼!
XML 代碼
<Button
android:id="@ id/btn_1"
android:layout_width="150dp"
android:layout_height="48dp"
android:layout_marginTop="32dp"
android:background="@drawable/custom_buttons"
android:text="Characters"
android:textColor="@color/white"
android:textStyle="normal"
app:flow_verticalAlign="top"
app:layout_constraintBottom_toBottomOf="@ id/imageView4"
app:layout_constraintEnd_toEndOf="@ id/imageView4"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/toolbar"
app:layout_constraintVertical_bias="0.31" />
<Button
android:id="@ id/btn_2"
android:layout_width="150dp"
android:layout_height="48dp"
android:background="@drawable/custom_buttons"
android:text="Matchs Up"
android:textColor="@color/white"
app:layout_constraintBottom_toBottomOf="@ id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@ id/imageView"
app:layout_constraintTop_toBottomOf="@ id/imageView4"
app:flow_verticalAlign="center"/>
<Button
android:id="@ id/btn_3"
android:layout_width="150dp"
android:layout_height="48dp"
android:background="@drawable/custom_buttons"
android:text="glossary"
android:textColor="@color/white"
app:layout_constraintBottom_toBottomOf="@ id/imageView5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@ id/imageView5"
app:layout_constraintTop_toBottomOf="@ id/imageView" />
主活動.KT
val button: Button = findViewById<Button>(R.id.btn_1)
val button: Button = findViewById<Button>(R.id.btn_2)
val button: Button = findViewById<Button>(R.id.btn_3)
button.setOnClickListener{
val intent = Intent(this, Page1::class.java)
startActivity(intent)
}
button.setOnClickListener{
val intent = Intent(this, Page2::class.java)
startActivity(intent)
}
button.setOnClickListener{
val intent = Intent(this, Page3::class.java)
startActivity(intent)
}
我在“val button : Button”上有一個紅色錯誤 -> 沖突宣告:val button: Button, val button: Button。
我做錯了什么,有沒有更好的方法來做到這一點?
uj5u.com熱心網友回復:
同一作用域中不能有 2 個或更多同名變數。
val button 意思是: “創建一個名為 button的新(不可變)變數”。要解決此問題,請為每個變數分配一個唯一名稱。例如:
val button1: Button = findViewById<Button>(R.id.btn_1)
val button2: Button = findViewById<Button>(R.id.btn_2)
val button3: Button = findViewById<Button>(R.id.btn_3)
button1.setOnClickListener{
val intent = Intent(this, Page1::class.java)
startActivity(intent)
}
button2.setOnClickListener{
val intent = Intent(this, Page2::class.java)
startActivity(intent)
}
button3.setOnClickListener{
val intent = Intent(this, Page3::class.java)
startActivity(intent)
}
我假設您是 Kotlin 的新手。強烈建議查看Kotlin 官方檔案并閱讀Kotlin 中的基本語法或變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402222.html
上一篇:從同一個父類的另一個類訪問物件
