我是學習 Kotlin 和 android studio 的新手,想要實作一個按鈕,可以在單擊時來回切換文本。
例如,當我第一次單擊按鈕時,我的 textView 顯示為 true。當我再次單擊它時,它是不可見的,之后可見等。
我的 textView 的一個簡單的切換按鈕。
我不知道我是否需要一個回圈,或者我將如何通過在每秒鐘單擊一次時禁用該元素來繼續。
MainActivity.kt
btn_click_me.setOnClickListener {
textViewToggle.text = "Showing text"
}
activity_main.xml
<Button
android:id="@ id/btn_click_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="42dp"
android:layout_marginBottom="7dp"
android:text="@string/visa_g_m_texten"
app:layout_constraintBottom_toTopOf="@ id/textViewToggle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UsingOnClickInXml" />
<TextView
android:id="@ id/textViewToggle"
android:layout_width="355dp"
android:layout_height="0dp"
android:layout_marginBottom="480dp"
android:text="@string/denna_text_kommer_togglas_p_och_av_m_r_man_klickar_p_knappen_ovanf_r"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
每一個答案都非常感謝!
// 最大限度
uj5u.com熱心網友回復:
你可以試試這個:
1-宣告一個布爾變數,以保存點擊狀態:
var boolean = true
2- 在button.setOnClickListener里面添加:
boolean = !boolean
此行將在每次單擊時更改布林值。(符號“!”表示“逆”,所以如果“boolean”為真,則“!boolean”為假)。
3-添加您的 if 陳述句,例如:
if (boolean) { // means: if the value is true
textView.text = "true"
} else {
textView.text = "false"
}
您的最終代碼將如下所示:
button.setOnClickListener {
boolean = !boolean // inverse the value when this button is clicked
if (boolean) {
textView.text = "true"
} else {
textView.text = "false"
}
}
如果您只想更改文本的可見性,只需撰寫以下代碼:
var boolean = true
button.setOnClickListener {
boolean = !boolean
textView.isVisible = boolean
}
uj5u.com熱心網友回復:
在螢屏上顯示/隱藏組件:
// Hide
view.visibility = View.GONE
// Show
view.visibility = View.VISIBLE
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511235.html
