Как установить значение целого числа внутри элемента TextView? - PullRequest
1 голос
/ 12 февраля 2020

Чего я хочу достичь?

  • Я хочу, чтобы элемент TextView обновлялся каждый раз, когда генерируется новое значение для int x и int y.
  • Я хочу, чтобы текст Correct answer и текст False answer отображались не в журнале, а как элемент textView.

Что у меня есть?

  1. Подсчет всего кода x*y (ответ z)
  2. Генерация кода x, y и z
  3. Сравнение кодов z и answer (ответ пользователя)

Что мне нужно?

  • textView элемент, отображающий «x * y» (где и x, и y должны быть целыми числами в textView) и обновляется после каждого x и y обновления значения
  • Некоторый элемент, который может отображать Correct или Incorrect в качестве другого элемента textView, показанного под элементом Button вместо записей журнала

Код

MainActivity. java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.util.Random;

public class MainActivity extends AppCompatActivity {


    private EditText textBox;
    private int z , answer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textBox=findViewById(R.id.editText);
        setActual();
    }

    private void setActual(){
        Random random = new Random();

        int[] firstNum = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        int x = firstNum[random.nextInt(firstNum.length)];/*Here program should put a random number out of firstNum array*/
        int[] secondNum = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int y = secondNum[random.nextInt(secondNum.length)];/*Here program should put a random number out of secondNum array*/
        z = x*y;
    }

    public void onCheck(View view){

        this.answer = Integer.parseInt(textBox.getText().toString());

        if(answer == z){
            Log.d("TAG", "Correct."); // right answer
        }
        else{
            Log.d("TAG", "Incorrect."); // wrong answer
        }


    }


}

Activity_main. 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:hint="Enter you guess"
        android:inputType="numberDecimal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.333"
        tools:layout_editor_absoluteX="0dp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check"
        android:layout_margin="20dp"
        android:onClick="onCheck"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

Ответы [ 2 ]

1 голос
/ 12 февраля 2020

Решение: Добавьте еще два TextView в ваш view и обновите их соответствующим образом.

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

Активность:

/* package & imports.. */

public class MainActivity extends AppCompatActivity {

    private EditText textBox;
    private int z, answer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textBox = findViewById(R.id.editText);
        setActual();
    }

    private void setActual() {
        Random random = new Random();
        int x = random.nextInt(10) + 1; //you get a random number between 0 and 9 then add 1 to get 1 - 10, no need to use array.. 
        int y = random.nextInt(10) + 1;
        z = x * y;
        String hintStr = x + " * " + y;
        ((TextView) findViewById(R.id.hintTextView)).setText(hintStr);
    }

    public void onCheck(View view) {

        this.answer = Integer.parseInt(textBox.getText().toString());
        String res = "Incorrect";
        if (answer == z) {
            res = "Correct";
            Log.d("TAG", "Correct."); // right answer

            setActual(); // let's regenerate values 

        } else {
            Log.d("TAG", "Incorrect."); // wrong answer
        }
        ((TextView) findViewById(R.id.result_text_view)).setText(res);
    }
}

И ваше мнение: Просто добавили 2 текстовых представления, первое, как вы сказали, чтобы указать x * y как целые числа, так и другой, чтобы показать результат.

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/hintTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="x * y"
        app:layout_constraintBottom_toTopOf="@+id/editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:hint="Enter you guess"
        android:inputType="numberDecimal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.333"
        tools:layout_editor_absoluteX="0dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:onClick="onCheck"
        android:text="Check"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="20dp" />

    <TextView
        android:id="@+id/result_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintVertical_bias="0.316" />


</androidx.constraintlayout.widget.ConstraintLayout>
0 голосов
/ 12 февраля 2020

В методе onCreate получите ссылку на свои TextView s, используя их ID, так же, как вы указали для EditText. Затем, после изменения значений переменных x, y, & z и любых других переменных, установите текст в TextView следующим образом:

textView.setText("" + x + " * " + y + " = " + z);

answerIsCorrectText.setText("" + (x*y=z) ? "Correct!" : "Incorrect :(");

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...