为什么 Switch Compatible 在调用 onCheckedChanged 时导致片段中出现空指针

why is Switch Compat causing null pointer in fragment when calling onCheckedChange

相当说明性的标题 这是 xml

        <android.support.v7.widget.SwitchCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/mySwitch"
        app:showText="false"
        android:textOn="On"
        android:textOff="Off"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin" />

这是我在片段中所做的主要工作

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.intro_frag, container, false);
    getPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    switchCompat = (SwitchCompat) getActivity().findViewById(R.id.mySwitch);

    return rootView;

}

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    switchCompat.setOnCheckedChangeListener(new   
    CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean 
        isChecked) {
            if (isChecked) {
               //do stuff
            }
            else if (!isChecked){
               //do other stuff
            }
        }
    });

行 switchCompat.setOnCheckedChangeListener 导致空指针异常,没有它一切运行良好我搜索了这个问题并找到了一些修复,比如需要文本和东西的开关,但我无法让它工作,有人能帮忙吗?

你的错误是:

getActivity()

更改为:

switchCompat = (SwitchCompat) rootView.findViewById(R.id.mySwitch);