我将MainActivity用作FragmentActivity,将TabsPagerAdapter用作FragmentPagerAdapter。 我将状态栏作为片段(以及选项卡的页面)并使用此代码向片段添加开关,在事件期间没有任何事情发生。
public class Statusbar extends Fragment implements OnCheckedChangeListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mLinearLayout = (View) inflater.inflate(R.layout.statusbar_fragment,
container, false);
Switch s = (Switch) getActivity().findViewById(R.id.swt1);
if (s != null) {
s.setOnCheckedChangeListener(this);
}
return mLinearLayout;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(getActivity(), "hi",
Toast.LENGTH_SHORT).show();
}
}
可能是什么问题?如果我删除这个:
if (s != null) { ... }
它因nullpointerexception而崩溃。
答案 0 :(得分:0)
你有这个:
View mLinearLayout = (View) inflater.inflate(R.layout.statusbar_fragment,
container, false);
Switch s = (Switch) getActivity().findViewById(R.id.swt1);
将其更改为:
View mLinearLayout = (View) inflater.inflate(R.layout.statusbar_fragment,
container, false);
Switch s = (Switch) mLinearLayout .findViewById(R.id.swt1);