在Fragement中添加Toast to TTS按钮时,我收到此错误“无法解析方法'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();
}
}
}
答案 0 :(得分:1)
new TextToSpeech(HomeFragment.this
您应该使用getActivity()
。
返回此片段当前关联的FragmentActivity 用。
Toast.makeText(getActivity(), "Not Supported", Toast.LENGTH_SHORT).show();
new TextToSpeech(getActivity()
<强>最后强>
toSpeech = new TextToSpeech(getActivity(), 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(getActivity(), "Not Supported", Toast.LENGTH_SHORT).show();
}
}
});
答案 1 :(得分:0)
首先,
在您的代码中,您提供了 HomeFragment.this ,这在片段中是不合适的。
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();
}
}
});
您需要使用getActivity()更改 HomeFragment.this,并在代码中使用getActivity()更改 getApplicationContext(),如下所示: -
toSpeech = new TextToSpeech(getActivity(), 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(getActivity(), "Not Supported", Toast.LENGTH_SHORT).show();
}
}
});
第二个选项
如果使用getActivity()仍然无法正常使用Toast,那么您也可以尝试
getActivity().getBaseContext();
如下: -
Toast.makeText(getActivity().getBaseContext(), "Not Supported", Toast.LENGTH_SHORT).show();