我在getApplicationContext上的公共视图onCreateView上出现错误,似乎它在我的HomeFragment中无法正常工作,但是当我在我的MainAcitivity中尝试这个时,它可以工作。有没有人遇到过这个?
提前致谢!
这是我的代码:
package com.thesis.artificialintelligence;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Locale;
public class HomeFragment extends Fragment {
private TextView resultTEXT;
private TextView resultTEXT2;
TextToSpeech t1;
private String package_calculator = "com.android.calculator2";
private String class_calculator ="com.android.calculator2.Calculator";
private String package_camera = "com.android.camera";
private String class_camera ="com.android.camera.Camera";
private String package_contacts = "com.android.contacts";
private String class_contacts = "com.android.contacts.Contacts";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Inflate the layout for this fragment
rootView.findViewById(R.id.TVresult);
rootView.findViewById(R.id.TVresult2);
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() // There`s an Error here at getApplicationContext()
{
@Override
public void onInit(int status)
{
if(status != TextToSpeech.ERROR)
{
t1.setLanguage(Locale.UK);
}
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach()
{
super.onDetach();
}
}
答案 0 :(得分:1)
片段没有getApplicationContext()
方法。
TextToSpeech
只需要一个上下文,因此您可以将其替换为getActivity()
。
如果您真的想要应用程序上下文,请执行getActivity().getApplicationContext()
答案 1 :(得分:0)
如果您使用的是片段,请将getApplicationContext()
替换为getActivity()
和getContext()
。
答案 2 :(得分:0)
亲爱的,您可以使用
获取上下文getActivity().getApplicationContext();