选项卡中的错误膨胀开关按钮

时间:2016-05-14 10:05:24

标签: android

我在选项卡

中给开关按钮充气时遇到问题

我的serieb_tab.java是:

public class serieb_calendario extends Fragment{

Switch switchButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    switchButton = (Switch)getView().findViewById(R.id.serieb_calendar_switch);
    switchButton.setChecked(false);

    switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
            if (bChecked) {
                Log.d("Swirch", "on");
            } else {
                Log.d("Swirch", "on");
            }
        }
    });


    return inflater.inflate(R.layout.sereib_calendario, container, false);
}

}

回溯是:

FATAL EXCEPTION: main

Process: basket.amatoripescara.it.amatoripescarabakset, PID: 19021
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at basket.amatoripescara.it.amatoripescarabakset.serieb_calendario.onCreateView(serieb_calendario.java:24)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)

似乎问题是返回视图。

提前致谢。

1 个答案:

答案 0 :(得分:0)

getView()为null,因为尚未创建视图,并且您希望在其中查找视图,因此请更改

switchButton = (Switch)getView().findViewById(R.id.serieb_calendar_switch);

View view=inflater.inflate(R.layout.sereib_calendario, container, false);

switchButton = (Switch)view.findViewById(R.id.serieb_calendar_switch);

并将return语句更改为

return view;