在Fragment中以编程方式创建复选框

时间:2016-08-05 09:53:13

标签: android android-checkbox programmatically-created

我正在尝试在Fragment中创建一个复选框。我不能让它正常工作。 这是片段的代码:

 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的视图?

1 个答案:

答案 0 :(得分:3)

参见片段生命周期,您无法在OnCreate()中获取视图窗口小部件,因为它在OnCreateView();

中膨胀

enter image description here

    @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;
    }