我正在尝试重用通过使用片段显示的View(.xml
文件)。问题是,由于我重复使用该视图,因此我需要根据用户选择的课程名称重命名TextView's
文本值。
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();
}
}
}
我试过
LessonStartFragment lessonStartFragment = new LessonStartFragment();
TextView tv = lessonStartFragment.getView().findViewById(v.getId());
tv.setText(lessonName);
但它返回
java.lang.NullPointerException:尝试调用虚拟方法' android.view.View android.view.View.findViewById(int)'在空对象引用上
我认为我从v.getId()
获得的ID与片段视图组件中的实际ID不匹配。
每个button
(btnLesson1
,btnLesson2
,btnLesson3
......等等......)的标题都设置在button
&#39 ; s文本。我正在尝试将其文本设置为片段(LessonStartFragment
)Textview
。
我该怎么办呢?
我很感激任何帮助。
感谢。
答案 0 :(得分:0)
尝试像这样强制按钮: -
btnLesson1 = (Button)view.findViewById(R.id.multiplication_lesson1);
btnLesson2 = (Button)view.findViewById(R.id.multiplication_lesson2);
btnLesson3 = (Button) view.findViewById(R.id.multiplication_lesson3);
btnLesson4 = (Button) view.findViewById(R.id.multiplication_lesson4);
btnLesson5 = (Button)view.findViewById(R.id.multiplication_lesson5);
btnLesson6 = (Button)view.findViewById(R.id.multiplication_lesson6);