-1

Написал программу, которая выполняет следующий функционал: 1) заносятся данные в TextInputLayout; 2) при нажатии на Button эти данные считаются и выводятся в textview. Кнопка нажимается, но подсчёта не происходит. Activity.kt файл:

class CalculatorActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_calculator)
        val mybth = findViewById<Button>(R.id.mybth)
        mybth.setOnClickListener{
            val editweight = findViewById<EditText>(R.id.urweighttext)
            val editheight = findViewById<EditText>(R.id.textInputLayout6)
            val editage = findViewById<EditText>(R.id.textinput1)
            val textView2 = findViewById<TextView>(R.id.textView2)
            val c: Double
            val S1: String = editweight.text.toString()
            val S2: String = editheight.text.toString()
            val S3: String = editage.text.toString()
            var a: Int = Integer.parseInt(S1)
            var b: Int = Integer.parseInt(S1)
            var d: Int = Integer.parseInt(S1)
            c = 10 * a + 6.25 * b + 5 * d
            textView2.text = c.toString()
        }
    }
}

XML файл:

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/editage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CalculatorActivity">


    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/gradient"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintBottom_toTopOf="@id/toolbar2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/calculator"
        android:textColor="#FFFFFF"
        android:textSize="24sp"
        android:textStyle="normal"
        app:layout_constraintBottom_toBottomOf="@+id/toolbar2"
        app:layout_constraintEnd_toEndOf="@+id/toolbar2"
        app:layout_constraintStart_toStartOf="@+id/toolbar2"
        app:layout_constraintTop_toTopOf="@+id/toolbar2" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/urweighttext"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="280dp"
        android:hint="@string/yourweight"
        app:boxStrokeColor="@color/gradient1"
        app:hintTextColor="@color/gradient1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar2"
        tools:ignore="InvalidId">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/editweight"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout6"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="150dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="140dp"
        android:hint="@string/yoursize"
        app:boxStrokeColor="@color/gradient1"
        app:hintTextColor="@color/gradient1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar2">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/editheight"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textinput1"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="290dp"
        android:layout_marginTop="25dp"
        android:layout_marginEnd="15dp"
        android:hint="@string/urage"
        app:boxStrokeColor="@color/gradient1"
        app:hintTextColor="@color/gradient1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar2">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>



    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="124dp"
        android:text="@string/men"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar2" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="@string/women"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/checkBox" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:text="@string/pol"
        app:layout_constraintBottom_toTopOf="@+id/checkBox"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/urweighttext"
        app:layout_constraintVertical_bias="0.789" />

    <TextView
        android:clickable = "true"
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/calculate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mybth"
        app:layout_constraintVertical_bias="0.241"
        android:focusable="true" />

    <Button
        android:id="@+id/mybth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/calculate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/checkBox2"
        app:layout_constraintVertical_bias="0.142" />


</androidx.constraintlayout.widget.ConstraintLayout>

введите сюда описание изображения

5
  • У вас а б и ц переменные явно неправильно инициализированы
    – ЮрийСПб
    22 апр 2021 в 16:04
  • В чём заключается ошибка? Сейчас поменял val на var и в скобках заметил, что везде S1 стояло, теперь код выглядит так, но не работает: ``` var a: Int = Integer.parseInt(S1) var b: Int = Integer.parseInt(S2) var d: Int = Integer.parseInt(S3) var c: Double ```
    – Tsvetkov
    22 апр 2021 в 16:19
  • не работает - это очень не информативно. Объясните подробнее. Выведите в логи значения всех переменных на всех этапах логики - наверняка заметите где и что не так.
    – ЮрийСПб
    22 апр 2021 в 16:39
  • Еще код можно попытаться отладить. Ставите точку останова в обработчике нажатия кнопки и все сразу станет понятно. developer.android.com/studio/debug 22 апр 2021 в 17:45
  • Сравните типы в разметке и в коде, тут у вас явные нестыковки. Пример findViewById<EditText>(R.id.textinput1) 22 апр 2021 в 17:49

1 ответ 1

1

Ваша ошибка состоит в том, что вместо TextInputEditText, в которых содержится нужный вам текст, вы обращаетесь к обрамляющим их TextInputLayout, нужным для красивого движения подсказки в верхний левый угол поля. Поэтому для того, чтобы приложение заработало, нужно во-первых дать имя третьему TextInputEditText, которое содержит возраст. То есть добавить id - editage :

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textinput1"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="290dp"
    android:layout_marginTop="25dp"
    android:layout_marginEnd="15dp"
    android:hint="@string/urage"
    app:boxStrokeColor="@color/gradient1"
    app:hintTextColor="@color/gradient1"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/toolbar2">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/editage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>

В классе MainActivity обратиться именно к TextInputEditText'ам:

val editweight = findViewById<TextInputEditText>(R.id.editweight)
val editheight = findViewById<TextInputEditText>(R.id.editheight)
val editage = findViewById<TextInputEditText>(R.id.editage)

Далее заменить S1 в двух местах на S2, S3 :

var a: Int = Integer.parseInt(S1)
var b: Int = Integer.parseInt(S2)
var d: Int = Integer.parseInt(S3)

Должно заработать, как мне кажется.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.