我正在使用三个类 - MainActivity,Frag1,BottomSheetFrag。 我使用一个简单的接口,通过MainAc将一个对象从BottomSheet发送到Frag1。哪个功能完美。但是当recyclerView设置适配器时,我得到了NullPointerException。
BottomSheet:
private EditText et_name;
private EditText et_contact;
private Button btn_ok;
ICommunic comm;
private BottomSheetBehavior.BottomSheetCallback
mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN)
dismiss();
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
}
};
@Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
View v = View.inflate(getContext(), R.layout.fragment_BS, null);
et_name = v.findViewById(R.id.et_nameV);
et_contact = v.findViewById(R.id.et_contactV);
btn_ok = v.findViewById(R.id.btn_save);
btn_ok.setOnClickListener((View view) -> {
Person p = new Person(et_name.getText().toString(), et_contact.getText().toString())
comm.AddPerson(p);
});...
MainActivity实现接口
...
@Override
public void AddPerson(Person p) {
Frag1.getPerson(p);
}
Frag1
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<Person> listPerson;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.frag1, container, false);
recyclerView = view.findViewById(R.id.rv_person);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public void getPerson(Person p) {
listPerson.add(p);
adapter = new AdapterRecV(getActivity(), listAluno);
recyclerView.setAdapter(adapter);
}
答案 0 :(得分:0)
通过定义List和适配器为静态,我能够达到预期的效果。