我尝试在RecyclerView
为空时显示一个TextView
。
但是,即使RecyclerView
显示项目,ListAdapter
的getItemCount()
始终返回0。
Fragment.java
public class ProjectsFragment extends Fragment {
private RepoViewModel repoViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FloatingActionButton floatingActionButton = ((MainActivity) requireActivity()).getFloatingActionButton();
floatingActionButton.setVisibility(View.VISIBLE);
return inflater.inflate(R.layout.fragment_projects, container, false);
}
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textview_no_project = view.findViewById(R.id.textview_no_project);
RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity().getApplicationContext()));
final RepoListAdapter adapter = new RepoListAdapter(new RepoListAdapter.RepoDiff());
if (adapter.getItemCount() == 0) {
recyclerView.setVisibility(View.INVISIBLE);
textview_no_project.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
textview_no_project.setVisibility(View.INVISIBLE);
}
recyclerView.setAdapter(adapter);
repoViewModel = new ViewModelProvider(requireActivity()).get(RepoViewModel.class);
repoViewModel.getAllRepos().observe(getViewLifecycleOwner(), adapter::submitList);
}
}
RepoListAdapter.java
public class RepoListAdapter extends ListAdapter<Repo, RepoViewHolder> {
public RepoListAdapter(@NonNull DiffUtil.ItemCallback<Repo> diffCallback) {
super(diffCallback);
}
@NonNull
@Override
public RepoViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
return RepoViewHolder.create(viewGroup);
}
@Override
public void onBindViewHolder(RepoViewHolder holder, int position) {
Repo current = getItem(position);
holder.bind(current.getName());
}
public static class RepoDiff extends DiffUtil.ItemCallback<Repo> {
@Override
public boolean areItemsTheSame(@NonNull Repo oldItem, @NonNull Repo newItem) {
return oldItem == newItem;
}
@Override
public boolean areContentsTheSame(@NonNull Repo oldItem, @NonNull Repo newItem) {
return oldItem.getName().equals(newItem.getName());
}
}
}
非常感谢任何帮助。