I am learning Android Studio and I have a question: I wanna say something in chinese and there compare the word/phrase I said with the one that was displayed at the screen. And if these two words are equals - make text green. else - red. But it always red after I press the mic button. Will appriciate any help
public class SpeakingActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT = 1000;
TextView mTextView;
TextView input;
ImageButton mImageButton;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speakingfromhome);
button = findViewById(R.id.nextSpeaking);
mTextView = findViewById(R.id.output);
mImageButton = findViewById(R.id.image);
input = findViewById(R.id.input);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changeQuestions();
mTextView.setTextColor(Color.BLACK);
}
});
mImageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
speak();
checkIfCorrect();
}
});
}
private void checkIfCorrect() {
if (input.toString().equals(mTextView.toString()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}
private void changeQuestions() {
input.setText("基辅");
}
private void speak() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINA.toString());
try {
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
} catch (Exception ex) {
Toast.makeText(this, "" ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mTextView.setText(result.get(0));
}
break;
}
}
}
}
CodePudding user response:
The function checkIfCorrect() is the problem
Change it to:
input.toString()
->input.getText()
mTextView.toString()
->mTextView.getText()
Like:
input.getText().equals(mTextView.getText())
with getText()
get the text of the TextView, doint input.toString()
convert the object TextView to String
your checkIfCorrect function must look like:
private void checkIfCorrect() {
if (input.getText().equals(mTextView.getText()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}
A better way:
private void checkIfCorrect() {
mTextView.setTextColor((input.getText().equals(mTextView.getText())) ? Color.GREEN : Color.RED )
}