Android 在片段中以编程方式创建复选框

Android 在片段中以编程方式创建复选框,android,android-checkbox,programmatically-created,Android,Android Checkbox,Programmatically Created,我试图在片段中创建一个复选框。我没法让它正常工作。 以下是我的片段代码: public class DriverFragment extends Fragment { public DriverFragment(){ } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);

我试图在片段中创建一个复选框。我没法让它正常工作。 以下是我的片段代码:

 public class DriverFragment extends Fragment {

    public DriverFragment(){

    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        CheckBox check = new CheckBox(getActivity());
        check.setText("ff");
        check.setPadding(10,10,10,10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(5,5,5,5);
        params.gravity = Gravity.NO_GRAVITY;
        check.setLayoutParams(params);
        check.setGravity(Gravity.CENTER);
        LinearLayout lin = (LinearLayout)getView().findViewById(R.id.driverLayout);
        lin.addView(check);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment_driver,container,false);
    }
}
我得到这个错误:

尝试在空对象引用上调用虚拟方法“android.view.view android.view.view.findViewById(int)”


我得到这个是因为带有LinearLayout的视图尚未加载吗?

请参见片段生命周期您无法在
OnCreate()中获得视图小部件,因为它在
OnCreateView()中膨胀


也添加你的
R.layout.fragment\u驱动程序?你是什么意思?我不明白。将R.layout.fragment\u驱动程序添加到什么?您的复选框创建代码应该在
onCreateView()
方法中,因为您的视图在该方法中膨胀。@PiyushGupta我已将其移动到>>onCreateView(),我得到了与@SohailZahid相同的错误检查答案。这是正确的答案@mrg3tools如果有帮助,那太好了。请打勾并投票。@mrg3tools没问题。快乐编码:)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_driver, container, false);

        CheckBox check = new CheckBox(getActivity());
        check.setText("ff");
        check.setPadding(10, 10, 10, 10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 5, 5, 5);
        params.gravity = Gravity.NO_GRAVITY;
        check.setLayoutParams(params);
        check.setGravity(Gravity.CENTER);

        LinearLayout lin = (LinearLayout) view.findViewById(R.id.driverLayout);
        lin.addView(check);

        return view;
    }