在Fragement中添加Toast to TTS按钮时,我收到此错误 "Cannot resolve method 'getApplicationContext()" 即使我尝试 getActivty()
. 和 getContext()
. ,然后出现更多的错误,这是祝酒词:
Toast.makeText(getApplicationContext(), "Not Supported", Toast.LENGTH_SHORT).show();
这是fragement代码:
TextToSpeech toSpeech;
int result;
EditText editText;
String text;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
editText = v.findViewById(R.id.editText);
toSpeech = new TextToSpeech(HomeFragment.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Locale locale = new Locale("tr-TR");
int result = toSpeech.setLanguage(locale);
} else {
Toast.makeText(getApplicationContext(), "Not Supported", Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
public void TTS(View view) {
switch (view.getId()) {
case R.id.bplay:
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
} else {
text = editText.getText().toString();
toSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
toSpeech.setSpeechRate((float) 0.8);
toSpeech.setPitch((float) 0.7);
}
break;
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (toSpeech != null) ;
{
assert toSpeech != null;
toSpeech.stop();
toSpeech.shutdown();
}
}
}
2 回答
你应该使用getActivity() .
Finally
在你的代码中,你给出了 HomeFragment.this ,这在片段中是不合适的 .
您需要更改 HomeFragment.this with getActivity() 并在代码中更改 getApplicationContext() with getActivity() ,如下所示: -
如果使用getActivity()仍然无法正常使用Toast,那么您也可以尝试
如下: -