如果中文单词相等,如何使文本变绿?



我正在学习Android Studio,我有一个问题:我想用中文说些什么,并将我所说的单词/短语与屏幕上显示的单词/短语进行比较。如果这两个单词相等,则将文本设置为绿色。否则——红色。但我按下麦克风按钮后,它总是红色的。非常感谢您的帮助

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;
}
}
}

}

函数checkIfCorrect()是问题

改为:

  • input.toString()->input.getText()
  • mTextView.toString()->mTextView.getText()

:

input.getText().equals(mTextView.getText())

getText()得到TextView的文本,点input.toString()转换对象TextView为字符串

你的checkIfCorrect函数必须看起来像:

private void checkIfCorrect() {
if (input.getText().equals(mTextView.getText()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}

一个更好的方法:

private void checkIfCorrect() {
mTextView.setTextColor((input.getText().equals(mTextView.getText())) ? Color.GREEN : Color.RED )
}