Плюс и минус кнопка с EditText - PullRequest
0 голосов
/ 22 июня 2019

У меня есть функционирующая кнопка с приращением и уменьшением, которая работает правильно.но мне нужно, чтобы я мог также ввести значение вручную с помощью EdidText.

Мой код следующий:

Activity.tk

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    internal var minteger = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        val plus = findViewById<Button>(R.id.increase)
        val minus = findViewById<Button>(R.id.decrease)

        plus.setOnClickListener {

            increaseInteger(plus)
        }



        minus.setOnClickListener {

            decreaseInteger(minus)
        }
    }

    fun increaseInteger(view: View) {
        minteger += 1
        display(minteger)

    }

    fun decreaseInteger(view: View) {
        minteger -= 1
        display(minteger)
    }

    private fun display(number: Int) {
        val displayInteger = findViewById<View>(
                R.id.integer_number) as TextView
        displayInteger.text = "" + number
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity">



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/decrease"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-" />

        <TextView
            android:id="@+id/integer_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="40dp"
            android:layout_marginTop="16dp"
            android:text="0"
            android:textStyle="bold"
            android:textSize="70sp" />

        <Button
            android:id="@+id/increase"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+" />
    </LinearLayout>


</LinearLayout>

Я изменил TextView с помощью EditText (@+id/integer_number)

Но когда я ввожу значение, которое не сохранено, я не могу найти способ сделать это значение введеннымв сохраненном EdidText, чтобы я мог увеличивать или уменьшать его.

Буду признателен за любые предложения по работе с моей кнопкой.

buton

1 Ответ

3 голосов
/ 22 июня 2019

В вашем xml смените на EditText:

<EditText
    android:id="@+id/integer_number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginLeft="40dp"
    android:layout_marginRight="40dp"
    android:layout_marginTop="16dp"
    android:text="0"
    android:inputType="number"
    android:textStyle="bold"
    android:textSize="70sp" />

Я добавил атрибут:

android:inputType="number"

, поэтому разрешены только цифры.
В вашем классе MainActivity добавьте этот импорт:

import kotlinx.android.synthetic.main.activity_main.*

, чтобы вы могли получить доступ ко всем элементам XML без необходимости findViewById().
Теперь вам не нужно сохранять значение EditText где-либо, потому что вы можете получить его в любое время:

integer_number.text.toString().toInt()

поэтому переменная minteger больше не нужна.
Измените код действия на это: импорт android.os.Bundle import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main. *

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        increase.setOnClickListener { increaseInteger() }
        decrease.setOnClickListener { decreaseInteger() }
    }

    fun increaseInteger() {
        display(integer_number.text.toString().toInt() + 1)
    }

    fun decreaseInteger() {
        display(integer_number.text.toString().toInt() - 1)
    }

    private fun display(number: Int) {
        integer_number.setText("$number")
    }
}

Я сделал и другие упрощения.
Вам не нужны аргументы для функций increaseInteger() и decreaseInteger().
Существует ограничение на максимальное и минимальное целочисленные значения.
Поэтому, если вы хотите быть в безопасности, вы должны также использовать блок try/catch внутри increaseInteger() и decreaseInteger(), чтобы избежать исключений.

...