Кнопка "Верно" и "Неверно" обновляет вопросы и отвечает - PullRequest
0 голосов
/ 17 июня 2020

Привет, делаю простой тест на сотрясение мозга. Имеет textView, а затем кнопку true и false, более верные ответы приводят к не диагностированному результату. Я хочу, чтобы каждый щелчок по кнопке "истина" или "ложь" обновлял текстовое представление до следующего вопроса. Кажется, ложный ответ ни к чему не приводит! Это хороший способ сделать это, или я должен попробовать что-то еще? Спасибо MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    int[] stringIdList = {R.string.Q1, R.string.Q2, R.string.Q3, R.string.Q4, R.string.Q5};
    int stringListCounter = 0;
    TextView text1;
    int concussued = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        text1 = findViewById(R.id.text1);
        button.setOnClickListener(this);
        Button negative=findViewById(R.id.button3);
        negative.setOnClickListener(this);

    }


    @SuppressLint("SetTextI18n")

    public void onClick(@NonNull View v) {
        int id = v.getId();

        if (id == R.id.button && stringListCounter < stringIdList.length - 1) {
            stringListCounter++;

            text1.setText(stringIdList[stringListCounter]);
        }
        concussued = concussued - 1;
    }



    public void onClick2(@NonNull View v) {

        int id = v.getId();


        if (id == R.id.button3 && stringListCounter < stringIdList.length - 1) {
            stringListCounter++;
            text1.setText(stringIdList[stringListCounter]);
        }
        concussued = concussued + 1;
    }

    public void onClick3(View v) {
        Button diagnose = findViewById(R.id.button2);
        diagnose.setOnClickListener(this);
        findViewById(R.id.text1);
        if (concussued >= 2) {
            text1.setText("Concussed!");

        } else {
            text1.setText("Not concussed");
        }
    }
}

MainActivity 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">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.176" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="308dp"
        android:onClick="onClick"
        android:text="True"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="167dp"
        android:layout_marginLeft="167dp"
        android:layout_marginTop="196dp"
        android:onClick="onClick3"
        android:text="Diagnose"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:onClick="onClick2"
        android:text="False"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>

1 Ответ

0 голосов
/ 17 июня 2020

Вы реализуете интерфейс View.OnClickListener, который имеет только один метод для реализации onClick:

    /**
     * Interface definition for a callback to be invoked when a view is clicked.
     */
    public interface OnClickListener {
        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        void onClick(View v);
    }

Ваши методы onClick2 и onClick3 не являются частью этого интерфейса и, следовательно, не являются называется. Кнопка False при нажатии вызывает метод onClick. Вы можете разместить там точку останова и отладить это.

Чтобы исправить эту проблему, вы можете использовать оператор switch:

 @SuppressLint("SetTextI18n")

    public void onClick(@NonNull View v) {
        switch(v.getId()) {
            case R.id.button:
                trueButtonClicked();
            break;
            case R.id.button2:
                diagnose();
            break;
            case R.id.button3:
                falseButtonClicked();
            break;
        }
    }

    public void trueButtonClicked() {
        if (stringListCounter < stringIdList.length - 1) {
            stringListCounter++;

            text1.setText(stringIdList[stringListCounter]);
        }
        concussued = concussued - 1;
    }

    public void falseButtonClicked() {
        if (stringListCounter < stringIdList.length - 1) {
            stringListCounter++;
            text1.setText(stringIdList[stringListCounter]);
        }
        concussued = concussued + 1;
    }

    public void diagnose() {
        if (concussued >= 2) {
            text1.setText("Concussed!");
        } else {
            text1.setText("Not concussed");
        }
    }
...