Как удалить свой ответ на вопрос из отображения второго ответа на вопрос в gridview? - PullRequest
0 голосов
/ 26 мая 2020

По сути, я пытаюсь изменить свой вопрос, проверяя, точно ли ответ соответствует другому текстовому представлению, поэтому сейчас моя проблема в том, как я могу удалить или обновить ответ на новый вопрос в android gridview ? (В сетке я помещаю кнопку с именем ответа)

Это последовательность действий для следующего вопроса, когда первый вопрос завершен, кнопка проверки go перейдет к следующему вопросу и также изменится ответы для gridview. Но в моем коде первый ответ на вопрос все еще находится в gridview, соединенном со вторым ответом на вопрос.

Вот мой Quiz.java:

    package com.example.activity.Main;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.activity.R;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class quiz extends AppCompatActivity{

    private ImageButton imageButton;
    private File soundfile = null;
    private GridView ll;
    private ImageButton check;
    private final ArrayList<String> buttonList = new ArrayList<>();
    ArrayAdapter<String> adapter;
    private TextView result , text_quiz;
    String lessons,TextCompare,speakTextTxt,tempDestFile ;
    HashMap<String, String> myHashRender = new HashMap<String, String>();
    int qtotal;

    private int cont = 1;
    private int nextStartIndex=1;
    TextView number;
    List<String> word;
    private int counter=1;
    MediaPlayer mMediaPlayer = new MediaPlayer();
    TextToSpeech mTts;
    String word_to_use;
    boolean g;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.quiz);
        number = findViewById(R.id.numberss);
        imageButton = findViewById(R.id.icon1);
        result = findViewById(R.id.result);
        check = findViewById(R.id.validate);
        text_quiz = findViewById(R.id.text_quiz);
        ll = findViewById(R.id.btnlay);
// ----------------------------------------------------------------------------------------------
        Intent intent1 = getIntent();
        final String ass = intent1.getStringExtra("lesson");
        word = new LinkedList<String>(Arrays.asList(ass.split("_")));
        Collections.shuffle(word);
        qtotal= word.size();

// ----------------------------------------------------------------------------------------------

        word_to_use = showmenextquestion();
        middle(showmenextquestion());
        start(showmenextquestion());
        audio(showmenextquestion());
    }
// end
// ----------------------------------------------------------------------------------------------




    private void start(String word_to_use) {




                    String arr[] = word_to_use.split(" ",2);
                    String fword = arr[0];
                    String rword = arr[1];
                    String reprword = rword.replaceAll("[a-z]", "*");
                    final String text = fword + " " + reprword;
                    SpannableString firstword = new SpannableString(text);
                    firstword.setSpan(new UnderlineSpan(), 0, fword.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    result.setText(firstword);

                    final String [] display = result.getText().toString().split("\\s");

                    final String[] words = word_to_use.split("\\s");
                    final int noOfBtns = words.length;
                    final Button[] btns = new Button[noOfBtns];
                    for(int i=0;i<noOfBtns;i++)
                    {
                        buttonList.add(words[i]);
                        Collections.shuffle(buttonList);
                        ll.removeAllViewsInLayout();
                        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, buttonList)
                        {
                            @Override
                            public View getView(int position, View convertView, ViewGroup parent) {
                                View row = null;
                                if(convertView == null)
                                {
                                    row = super.getView(position,convertView,parent);
                                    row.setBackgroundResource(R.drawable.btn_background);
                                }

                                return row;
                            }
                        };
                        adapter.notifyDataSetChanged();
                        ll.setAdapter(adapter);

                        ll.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            public void onItemClick(AdapterView parent, View v, int position, long id) {


                                if(position < noOfBtns) {

                                    String selectedItem = parent.getItemAtPosition(position).toString();
                                    String s2 = text_quiz.getText().toString();
                                    String [] s2_word = s2.split("\\s+");
                                    List<String> str = new LinkedList<String>(Arrays.asList(s2_word));
                                    if(str.remove(selectedItem))
                                    {
                                        StringBuilder builder = new StringBuilder();
                                        for(String details: str)
                                        {
                                            builder.append(details + " ");
                                        }
                                        text_quiz.setText(builder.toString());
                                            v.setBackgroundResource(R.drawable.btn_background);
                                    }else {

                                                v.setBackgroundResource(R.drawable.buttons4);
                                                text_quiz.append(selectedItem + " ");

                                    }
                                }

                                if (cont >= display.length) {
                                    cont = 0;
                                    nextStartIndex = 0;
                                }

                                result.setText(formatText(text, display[cont]));
                                cont++;

                            }
                        });

                }

            }
    private void middle(final String word_to_use) {
        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String answer = word_to_use;


                    if(text_quiz.getText().toString().trim().equals(answer.trim()))
                    {

                        final AlertDialog.Builder builder = new AlertDialog.Builder(quiz.this);
                        builder.setTitle("Correct")
                                .setMessage("please click ok to continue until the end")
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        if(counter < qtotal)
                                        {
                                            String next = showmenextquestion();
                                            text_quiz.setText("");
                                            middle(next);
                                            start(next);
                                            audio(next);

                                        }
                                        else
                                        {
                                            finish();
                                        }

                                    }
                                }).show();
                    }else
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                        builder.setTitle("Incorrect");
                        builder.setMessage("There is no Words.");
                        builder.setCancelable(true);

                        final AlertDialog dlg = builder.create();

                        dlg.show();

                        Handler mHandler = new Handler();
                        Runnable mRunnable = new Runnable () {

                            public void run() {
                                if(dlg != null && dlg.isShowing()) dlg.dismiss();
                            }
                        };
                        mHandler.postDelayed(mRunnable,1500);
                    }
                }

                /*if(TextCompare.compareTo(answer) != 0)
                {
                    new AlertDialog.Builder(quiz.this)
                            .setTitle("Correct")
                            .setMessage("please click ok to continue until the end")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    text_quiz.setText("");
                                    ll.removeAllViewsInLayout();
                                    start();
                                    dialog.dismiss();
                                }
                            }).show();

                }else
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                    builder.setTitle("Incorrect");
                    builder.setMessage("Your Answer is Incorrect.");
                    builder.setCancelable(true);

                    final AlertDialog dlg = builder.create();

                    dlg.show();

                    Handler mHandler = new Handler();
                    Runnable mRunnable = new Runnable () {

                        public void run() {
                            if(dlg != null && dlg.isShowing()) dlg.dismiss();
                        }
                    };
                    mHandler.postDelayed(mRunnable,2000);
                    text_quiz.setText("");
                }*/

        });
    }
    private void audio(String word_to_use) {

        /*speakTextTxt = showmenextquestion();*/
        speakTextTxt = word_to_use;
        myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, speakTextTxt);

        String exStoragePath = "";
        File appTmpPath = new File("/storage/emulated/0/Android/data/");
        boolean isDirectoryCreated = appTmpPath.mkdir();
        Log.d("MainActivity", "directory " + appTmpPath + " is created : " + isDirectoryCreated);
        String tempFilename = "tts.wav";
        tempDestFile = appTmpPath.getAbsolutePath() + File.separator + tempFilename;
        Log.d("MainActivity", "tempDestFile : " + tempDestFile);
        new MySpeech(speakTextTxt);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                final String path = "/storage/emulated/0/Android/data/tts.wav";
                try {
                    mMediaPlayer.setDataSource(path);
                } catch (IllegalArgumentException e1) {
                    e1.printStackTrace();
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                try {
                    mMediaPlayer.prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mMediaPlayer.setLooping(true);
                if(!mMediaPlayer.isPlaying())
                {
                    v.setBackgroundResource(R.drawable.ic_image_play);
                    mMediaPlayer.start();
                }
                else
                {
                    v.setBackgroundResource(R.drawable.ic_stop_black);
                    mMediaPlayer.pause();
                }
            }
        });

    }

    private String showmenextquestion() {
        if(counter < qtotal)
        {

                lessons = word.get(counter);
                TextCompare = word.get(counter);
                number.setText(counter + "/" + qtotal);

                counter++;

        }
        return lessons;
    }

    class MySpeech implements TextToSpeech.OnInitListener {

        String tts;

        public MySpeech(String tts)
        {
            this.tts = tts;
            mTts = new TextToSpeech(quiz.this, this);
        }

        @Override
        public void onInit(int status)
        {
            Log.v("log", "initi");
            int i = mTts.synthesizeToFile(speakTextTxt, myHashRender, tempDestFile);
        }
    }
    public CharSequence formatText(String base, String highlight) {
        int start = base.indexOf(highlight,nextStartIndex);
        nextStartIndex = start+highlight.length();
        SpannableString span = new SpannableString(base);
        if (start >= 0) {

            span.setSpan(new UnderlineSpan(), start, nextStartIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            return span;

        }

        return base;
    }

    @Override
    public void onBackPressed() {
        mMediaPlayer.stop();
       super.onBackPressed();
    }
}

, а это мой quiz.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"
    android:background="@drawable/faded_background2"
    tools:context=".Main.quiz">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline_left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="24dp" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline_right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_end="24dp" />


    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/top1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        app:layout_constraintBottom_toTopOf="@id/top2"
        app:layout_constraintEnd_toEndOf="@id/guideline_right"
        app:layout_constraintStart_toStartOf="@id/guideline_left"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guide_left_inside_top1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="550dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            />

        <TextView
            android:id="@+id/numberss"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:gravity="center"
            android:text="0/30"
            android:textColor="#000000"
            android:textSize="25sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="@id/guide_left_inside_top1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/top2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@drawable/buttons2"
        app:layout_constraintBottom_toTopOf="@+id/text_quiz"
        app:layout_constraintEnd_toEndOf="@id/guideline_right"
        app:layout_constraintStart_toStartOf="@id/guideline_left"
app:layout_constraintTop_toBottomOf="@id/top1"
        app:layout_constraintVertical_bias="0.144">

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guide_left_inside_constraint"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="90dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            />
        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guide_right_inside_constraint"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_end="30dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            />

        <ImageButton
            android:id="@+id/icon1"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:background="@drawable/buttons2"
            android:src="@drawable/ic_image_play"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@id/guide_left_inside_constraint"
            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/result"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:gravity="center"
            android:text="TextView"
            android:textColor="@color/palette1"
            android:textSize="25sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="@id/guide_left_inside_constraint"
            app:layout_constraintEnd_toEndOf="@id/guide_right_inside_constraint"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>
    <TextView
        android:id="@+id/text_quiz"
        android:layout_width="0dp"
        android:background="@drawable/buttons1"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:textColor="@color/palette1"
        android:gravity="center"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginTop="10dp"
        app:layout_constraintStart_toStartOf="@id/guideline_left"
        app:layout_constraintEnd_toStartOf="@id/guideline_right"
        app:layout_constraintTop_toBottomOf="@+id/top2"/>

    <GridView
        android:id="@+id/btnlay"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:columnWidth="100dp"
        android:gravity="center"
        android:horizontalSpacing="16dp"
        android:numColumns="7"
        android:stretchMode="spacingWidthUniform"
        android:verticalSpacing="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text_quiz"
        app:layout_constraintBottom_toTopOf="@id/footer_line"/>

    <View
        android:id="@+id/footer_line"
        android:layout_width="0dp"
        android:layout_height="1dp"
        android:layout_marginBottom="50dp"
        android:background="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />

    <ImageButton
        android:id="@+id/validate"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_check"
        android:layout_marginTop="15dp"
        android:background="@color/login_light"
        app:layout_constraintStart_toStartOf="@id/guideline_left"
        app:layout_constraintEnd_toStartOf="@id/guideline_right"
        app:layout_constraintTop_toBottomOf="@+id/footer_line"
        />
    <!--


        />



    -->

</androidx.constraintlayout.widget.ConstraintLayout>






<!--
<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=".Main.quiz">


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="50sp"
            android:paddingLeft="20sp"
            android:paddingRight="20sp">


            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/round_corners">

                <ImageButton
                    android:id="@+id/icon1"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center"
                    android:background="@drawable/round_corners"
                    android:src="@drawable/ic_image_play"
                    app:layout_constraintBottom_toBottomOf="parent"
                    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/text_quess"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="TextView"
                    android:textColor="@color/p10"
                    android:textSize="25sp"
                    android:textStyle="bold"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.269"
                    app:layout_constraintStart_toEndOf="@+id/icon1"
                    app:layout_constraintTop_toTopOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>

            <Button
                android:id="@+id/text_quiz"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginTop="10dp"
                android:background="@drawable/round_corners2"
                android:text="TextView"
                android:textStyle="bold"
                android:textSize="25sp"
                android:textColor="@color/p10"
                android:layout_gravity="center"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/round_corners3"
            android:layout_marginTop="35sp">
        </LinearLayout>
    </ScrollView>


</androidx.constraintlayout.widget.ConstraintLayout>-->
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...