Search code examples
androidandroid-studiofragmentfindviewbyid

Cannot resolve findViewById in fragment


i am trying to get id from fragment xml so here is the code the error is " Cannot resolve the method findViewById "

Is there anyway of which I can use findViewById in Fragment ?

public class Slide_Teacher_Add extends Fragment implements View.OnClickListener {

private EditText teacher_id_number;
private EditText teacher_fullname;
private EditText teacher_lesson;
private EditText teacher_contact;

private Button btn_add_teacher;

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

    View v = inflater.inflate(R.layout.activity_slide__teacher_add,container,false);
    return v;

    teacher_id_number = (EditText) findViewById(R.id.teacher_id_number);
    teacher_fullname = (EditText) findViewById(R.id.teacher_fullname);
    teacher_lesson = (EditText) findViewById(R.id.teacher_lesson);
    teacher_contact = (EditText) findViewById(R.id.teacher_contact);

    btn_add_teacher = (Button) findViewById(R.id.btn_add_teacher);


    btn_add_teacher.setOnClickListener(this);
}

Solution

  • You can use onViewCreated function without need to Inflate view. such as :

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        view.findViewById(...);
        //....
    }
    

    Or You must call findViewById function from v object class (View). such as :

    teacher_id_number = (EditText) v.findViewById(R.id.teacher_id_number);