RecyclerView 不显示片段中的项目,但在 Activity 中有效
RecyclerView does not show items in Fragment, but works in Activity
免责声明:在搜索了整个 Whosebug 之后,我还没有找到解决方案。
我之前在另一个 Activity 中成功使用过 RecyclerView,所以我将该代码移植到片段中。我不确定为什么这些项目没有显示在 RecyclerView 中。经过调试,Fragment_Upcoming_Activities class 似乎没有调用 ActivitiesAdapter 方法,例如 onBindViewHolder() 和 onCreateViewHolder()。
Fragment_Upcoming_Activities.java:
private FirebaseAuth fAuth;
private FirebaseFirestore fStore;
private FirebaseUser mFirebaseUser;
private RecyclerView mFirestoreList;
private String currentUid;
private CollectionReference catRef;
private List<String> list_category = new ArrayList();
private ArrayAdapter<String> adapter_category;
private Spinner spCategories;
private ActivitiesAdapter adapter;
private View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container, @NonNull Bundle savedInstanceState) {
fAuth = FirebaseAuth.getInstance();
mFirebaseUser = fAuth.getCurrentUser();
fStore = FirebaseFirestore.getInstance();
currentUid = mFirebaseUser.getUid();
return inflater.inflate(R.layout.fragment_upcoming_activity, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
spCategories = view.findViewById(R.id.category_spinner);
mFirestoreList = view.findViewById(R.id.upcoming_act_recycleView);
//setUpCategoriesSpinner();
setupRecyclerView();
}
public void setUpCategoriesSpinner(){
//Department spinner population
catRef = fStore.collection("parent_categories");
list_category = new ArrayList<>();
adapter_category = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list_category);
adapter_category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter_category);
spCategories.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getSelectedItem();
displayUserData(selected);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
catRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String categoryName = document.getString("category_name");
list_category.add(categoryName);
}
adapter_category.notifyDataSetChanged();
}
}
});
}
public void displayUserData(String selected){
System.out.println("Selected category: " + selected);
Query query;
if (selected.equals("All Categories")) {
System.out.println("ALL");
query = fStore.collection("activities").whereEqualTo("act_purpose", "All");
} else {
System.out.println("OTHER");
String sub = selected.substring(selected.length() - 1);
System.out.println(sub);
int catNo = Integer.parseInt(sub);
query = fStore.collection("activities").whereEqualTo("act_purpose", "All").whereGreaterThan("act_category_number", sub).whereLessThan("act_category_number", sub).orderBy("act_category_number", Query.Direction.DESCENDING).orderBy("start_date", Query.Direction.DESCENDING);
}
//RecyclerOptions
FirestoreRecyclerOptions<ActivitiesModel> options = new FirestoreRecyclerOptions.Builder<ActivitiesModel>()
.setQuery(query, ActivitiesModel.class)
.build();
//View Holder
adapter.updateOptions(options);
}
private void setupRecyclerView(){
Query query = fStore.collection("activities");
//RecyclerOptions
FirestoreRecyclerOptions<ActivitiesModel> options = new FirestoreRecyclerOptions.Builder<ActivitiesModel>()
.setQuery(query, ActivitiesModel.class)
.build();
//View Holder
adapter = new ActivitiesAdapter(options);
mFirestoreList.setLayoutManager(new LinearLayoutManager(getContext()));
mFirestoreList.setAdapter(adapter);
adapter.setOnItemClickListener(new ActivitiesAdapter.OnItemClickListener() {
@Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
}
});
}
ActivitiesAdapter.java:
private ActivitiesAdapter.OnItemClickListener listener;
public ActivitiesAdapter(@NonNull FirestoreRecyclerOptions<ActivitiesModel> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull ActivitiesAdapter.ActivitiesHolder holder, int position, @NonNull ActivitiesModel model) {
String temp = model.getStart_date().toString().trim();
String[] temparray = temp.split(" ");
String startMonth = temparray[1];
String startDate = temparray[2];
String startYear = temparray[5];
String act_title = model.getAct_title();
String act_catName = model.getAct_category_name();
String pdHoursAndPoints = model.getPoints() + " Points · " + model.getHours() + " Hours";
holder.actTitle.setText(act_title);
holder.startDate.setText(startDate + "\n" + startMonth + "\n" + startYear);
holder.actCategory.setText(act_catName);
holder.actPointsAndHours.setText(pdHoursAndPoints);
}
@NonNull
@Override
public ActivitiesAdapter.ActivitiesHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_actlog,
parent, false);
return new ActivitiesAdapter.ActivitiesHolder(v);
}
class ActivitiesHolder extends RecyclerView.ViewHolder {
private TextView startDate, actTitle, actCategory, actPointsAndHours;
public ActivitiesHolder(View itemView) {
super(itemView);
startDate = itemView.findViewById(R.id.textview_startdate);
actTitle = itemView.findViewById(R.id.textview_act_title);
actCategory = itemView.findViewById(R.id.textview_act_category);
actPointsAndHours = itemView.findViewById(R.id.textview_pointsandhours_act);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION && listener != null){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
//insert intent for edit here
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(ActivitiesAdapter.OnItemClickListener listener){
this.listener = listener;
}
我太笨了,我忘了在onStart() 和onStop() 方法中添加。希望这对遇到同样问题的人有所帮助。
@Override
public void onStart() {
super.onStart();
if(adapter != null){
adapter.startListening();
}
}
@Override
public void onStop() {
super.onStop();
if(adapter != null){
adapter.stopListening();
}
}
免责声明:在搜索了整个 Whosebug 之后,我还没有找到解决方案。
我之前在另一个 Activity 中成功使用过 RecyclerView,所以我将该代码移植到片段中。我不确定为什么这些项目没有显示在 RecyclerView 中。经过调试,Fragment_Upcoming_Activities class 似乎没有调用 ActivitiesAdapter 方法,例如 onBindViewHolder() 和 onCreateViewHolder()。
Fragment_Upcoming_Activities.java:
private FirebaseAuth fAuth;
private FirebaseFirestore fStore;
private FirebaseUser mFirebaseUser;
private RecyclerView mFirestoreList;
private String currentUid;
private CollectionReference catRef;
private List<String> list_category = new ArrayList();
private ArrayAdapter<String> adapter_category;
private Spinner spCategories;
private ActivitiesAdapter adapter;
private View view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container, @NonNull Bundle savedInstanceState) {
fAuth = FirebaseAuth.getInstance();
mFirebaseUser = fAuth.getCurrentUser();
fStore = FirebaseFirestore.getInstance();
currentUid = mFirebaseUser.getUid();
return inflater.inflate(R.layout.fragment_upcoming_activity, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
spCategories = view.findViewById(R.id.category_spinner);
mFirestoreList = view.findViewById(R.id.upcoming_act_recycleView);
//setUpCategoriesSpinner();
setupRecyclerView();
}
public void setUpCategoriesSpinner(){
//Department spinner population
catRef = fStore.collection("parent_categories");
list_category = new ArrayList<>();
adapter_category = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list_category);
adapter_category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter_category);
spCategories.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getSelectedItem();
displayUserData(selected);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
catRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String categoryName = document.getString("category_name");
list_category.add(categoryName);
}
adapter_category.notifyDataSetChanged();
}
}
});
}
public void displayUserData(String selected){
System.out.println("Selected category: " + selected);
Query query;
if (selected.equals("All Categories")) {
System.out.println("ALL");
query = fStore.collection("activities").whereEqualTo("act_purpose", "All");
} else {
System.out.println("OTHER");
String sub = selected.substring(selected.length() - 1);
System.out.println(sub);
int catNo = Integer.parseInt(sub);
query = fStore.collection("activities").whereEqualTo("act_purpose", "All").whereGreaterThan("act_category_number", sub).whereLessThan("act_category_number", sub).orderBy("act_category_number", Query.Direction.DESCENDING).orderBy("start_date", Query.Direction.DESCENDING);
}
//RecyclerOptions
FirestoreRecyclerOptions<ActivitiesModel> options = new FirestoreRecyclerOptions.Builder<ActivitiesModel>()
.setQuery(query, ActivitiesModel.class)
.build();
//View Holder
adapter.updateOptions(options);
}
private void setupRecyclerView(){
Query query = fStore.collection("activities");
//RecyclerOptions
FirestoreRecyclerOptions<ActivitiesModel> options = new FirestoreRecyclerOptions.Builder<ActivitiesModel>()
.setQuery(query, ActivitiesModel.class)
.build();
//View Holder
adapter = new ActivitiesAdapter(options);
mFirestoreList.setLayoutManager(new LinearLayoutManager(getContext()));
mFirestoreList.setAdapter(adapter);
adapter.setOnItemClickListener(new ActivitiesAdapter.OnItemClickListener() {
@Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
}
});
}
ActivitiesAdapter.java:
private ActivitiesAdapter.OnItemClickListener listener;
public ActivitiesAdapter(@NonNull FirestoreRecyclerOptions<ActivitiesModel> options) {
super(options);
}
@Override
protected void onBindViewHolder(@NonNull ActivitiesAdapter.ActivitiesHolder holder, int position, @NonNull ActivitiesModel model) {
String temp = model.getStart_date().toString().trim();
String[] temparray = temp.split(" ");
String startMonth = temparray[1];
String startDate = temparray[2];
String startYear = temparray[5];
String act_title = model.getAct_title();
String act_catName = model.getAct_category_name();
String pdHoursAndPoints = model.getPoints() + " Points · " + model.getHours() + " Hours";
holder.actTitle.setText(act_title);
holder.startDate.setText(startDate + "\n" + startMonth + "\n" + startYear);
holder.actCategory.setText(act_catName);
holder.actPointsAndHours.setText(pdHoursAndPoints);
}
@NonNull
@Override
public ActivitiesAdapter.ActivitiesHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_actlog,
parent, false);
return new ActivitiesAdapter.ActivitiesHolder(v);
}
class ActivitiesHolder extends RecyclerView.ViewHolder {
private TextView startDate, actTitle, actCategory, actPointsAndHours;
public ActivitiesHolder(View itemView) {
super(itemView);
startDate = itemView.findViewById(R.id.textview_startdate);
actTitle = itemView.findViewById(R.id.textview_act_title);
actCategory = itemView.findViewById(R.id.textview_act_category);
actPointsAndHours = itemView.findViewById(R.id.textview_pointsandhours_act);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION && listener != null){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
//insert intent for edit here
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(ActivitiesAdapter.OnItemClickListener listener){
this.listener = listener;
}
我太笨了,我忘了在onStart() 和onStop() 方法中添加。希望这对遇到同样问题的人有所帮助。
@Override
public void onStart() {
super.onStart();
if(adapter != null){
adapter.startListening();
}
}
@Override
public void onStop() {
super.onStop();
if(adapter != null){
adapter.stopListening();
}
}