在我的应用中我有一个片段,我有任何复选框。当我开始使用TextToSpech时。我创建了一个没有片段的类似版本,它工作正常。但是,当我在片段中实现它时,它不起作用。她是我的代码:
public class OneFragment extends Fragment implements TextToSpeech.OnInitListener, CompoundButton.OnCheckedChangeListener {
private TextToSpeech tts;
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public OneFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
listView = (ListView) returnView.findViewById(R.id.listView);
adapter = new MyAdapter(getActivity(), getModel());
listView.setAdapter(adapter);
final CheckBox chk = (CheckBox)returnView.findViewById(R.id.checkBox);
chk.setOnCheckedChangeListener(OneFragment.this);
return returnView;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
tts = new TextToSpeech(getActivity(), this);
}
}
private List<Model> getModel() {
list.add(new Model("Linux", "S"));
list.add(new Model("Linux", "S"));
list.add(new Model("Linux", "S"));
list.add(new Model("Linux", "S"));
list.add(new Model("Linux", "S"));
return list;
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ITALIAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
startSpeak();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void startSpeak() {
tts.speak("Ciao", TextToSpeech.QUEUE_FLUSH, null);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox chk = (CheckBox)getActivity().findViewById(R.id.checkBox);
for (Model i: list ) {
if (chk.isChecked()) {
this.startSpeak();
}
}
}
}
这是部分LogCat结果:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
我该怎么办?
答案 0 :(得分:3)
我有一个片段,我有任何复选框
如果CheckBox
位于Fragment
的{{1}}布局内,则使用R.layout.fragment_one
从布局而不是OneFragment.this.getView()
访问CheckBox
:
getActivity()
或者将CheckBox chk = (CheckBox)OneFragment.this.getView().findViewById(R.id.checkBox);
声明为类级变量并在onCreateView中初始化它:
CheckBox chk