I am trying to reuse a View(.xml
file) which is displayed through the use of a fragment. The problem is, since I'm reusing the view, I need to rename the TextView's
text value based on the lesson name selected by user.
public class StudentMultiplicationFragment extends Fragment{
Button btnLesson1, btnLesson2, btnLesson3, btnLesson4, btnLesson5, btnLesson6;
public StudentMultiplicationFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.frag_studentmultiplication, container, false);
btnLesson1 = view.findViewById(R.id.multiplication_lesson1);
btnLesson2 = view.findViewById(R.id.multiplication_lesson2);
btnLesson3 = view.findViewById(R.id.multiplication_lesson3);
btnLesson4 = view.findViewById(R.id.multiplication_lesson4);
btnLesson5 = view.findViewById(R.id.multiplication_lesson5);
btnLesson6 = view.findViewById(R.id.multiplication_lesson6);
btnLesson1.setOnClickListener(new goToLessonStartFragment(btnLesson1.getText().toString()));
btnLesson2.setOnClickListener(new goToLessonStartFragment(btnLesson2.getText().toString()));
btnLesson3.setOnClickListener(new goToLessonStartFragment(btnLesson3.getText().toString()));
btnLesson4.setOnClickListener(new goToLessonStartFragment(btnLesson4.getText().toString()));
btnLesson5.setOnClickListener(new goToLessonStartFragment(btnLesson5.getText().toString()));
btnLesson6.setOnClickListener(new goToLessonStartFragment(btnLesson6.getText().toString()));
return view;
}
private class goToLessonStartFragment implements View.OnClickListener{
private String lessonName;
public goToLessonStartFragment(String lessonName){
this.lessonName = lessonName;
}
@Override
public void onClick(View v) {
LessonStartFragment lessonStartFragment = new LessonStartFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, lessonStartFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
I tried
LessonStartFragment lessonStartFragment = new LessonStartFragment();
TextView tv = lessonStartFragment.getView().findViewById(v.getId());
tv.setText(lessonName);
But it returns
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
I suppose that the id I get from v.getId()
doesn't match the actual id in fragments's view components.
Every button
(btnLesson1
,btnLesson2
,btnLesson3
...so on..) has a title which is set on button
's text. I am trying to set its text to the fragment's(LessonStartFragment
) Textview
.
How can I go about it?
I'd appreciate any help.
Thanks.