Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve findViewById in fragment [duplicate]

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);
}
like image 396
M Andre Juliansyah Avatar asked Dec 02 '18 09:12

M Andre Juliansyah


2 Answers

Firstly, you are calling findViewById() after the return statement so they wont be executed at all. Next, you need to call findViewById() on the context of a view as in view.findViewById(int); so rewrite the code as :

View v = inflater.inflate(R.layout.activity_slide__teacher_add,container,false);
teacher_id_number = v.findViewById(R.id.teacher_id_number); //Note this line
//other tasks you need to do
return v;

making sure the return is the last statement of the function.

like image 103
Yashovardhan99 Avatar answered Nov 13 '22 00:11

Yashovardhan99


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);
like image 23
Abbas m Avatar answered Nov 13 '22 02:11

Abbas m