1

I am trying to create a checkbox in my Fragment. I dont get it to work right. Here is my code for the 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);
    }
}

I am getting this error:

Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

Do I get this because the view with the LinearLayout has not been loaded yet?

Jas
  • 3,207
  • 2
  • 15
  • 45
mrg3tools
  • 29
  • 1
  • 8

1 Answers1

3

See Fragment life cycle you cant get view widgets in OnCreate() because its inflating in 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;
    }
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41