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);
}
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With