gpt4 book ai didi

java - 带复选框的 fragment 中的 NullPointEreException

转载 作者:行者123 更新时间:2023-12-01 21:59:16 26 4
gpt4 key购买 nike

在我的应用程序中,我有一个 fragment ,其中有任何复选框。当我启动 TextToSpech 时。我创建了一个类似的版本,没有 fragment ,并且工作正常。但是当我在 fragment 中实现它时,它不起作用。她是我的代码:

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

我该怎么办?

最佳答案

i have a fragment were i have any checkbox

如果 CheckBox 位于 R.layout.fragment_one 中的 Fragment 布局内,则使用 OneFragment.this.getView() 从布局访问 CheckBox 而不是 getActivity() :

CheckBox chk = (CheckBox)OneFragment.this.getView().findViewById(R.id.checkBox);

或者将 CheckBox chk 声明为类级别变量并在 onCreateView 内初始化它:

...
chk = (CheckBox)returnView.findViewById(R.id.checkBox);
...

关于java - 带复选框的 fragment 中的 NullPointEreException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com