Класс Button
Класс Button в пакете view
наследует
TextView
и рисует нажимаемую кнопку в XML.
Это не функция
Button
из material3 Compose.
Подпись задают android:text,
обработчик - через
setOnClickListener
или атрибут android:onClick.
Синтаксис
<Button
android:id="@+id/action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abcde" />
Параметры
| Параметр | Описание |
|---|---|
android:id |
Id кнопки для findViewById. |
android:layout_width |
Ширина кнопки на экране. |
android:layout_height |
Высота кнопки. |
android:text |
Подпись на кнопке. |
android:enabled |
Включена ли кнопка. Меняют и через
setEnabled.
|
Пример
Давайте поставим кнопку под текстом:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abcde" />
<Button
android:id="@+id/action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12345" />
</LinearLayout>
На экране сверху будет текст "abcde",
под ним кнопка с подписью "12345".
Пример
Давайте повесим onClick из Kotlin:
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val label = findViewById<TextView>(R.id.label)
findViewById<Button>(R.id.action).setOnClickListener {
label.text = "12345"
}
}
}
На экране по нажатию на кнопку
текст сменится на "12345".
Смотрите также
-
функция
Button,
кнопка Material в Jetpack Compose -
метод
setOnClickListener,
которым обрабатывают нажатие -
класс
TextView,
родитель Button для текста на виджете -
класс
LinearLayout,
который ставит кнопку под другими View