Я хочу, чтобы мои элементы RecyclerView распознавали, что на них нажимают. Я использую FirestoreRecyclerAdapter, привязку данных и пытаюсь сохранить все в MVVM. Я перепробовал множество различных решений, предлагаемых в StackOverflow и за его пределами, но ничего не помогло.
Как показано во фрагменте ниже, на данный момент я только пытаюсь заставить его выдать сообщение об ошибке, чтобы подтвердитьчто щелчок даже происходит.
AdminUserListFragment:
public class AdminUserListFragment extends Fragment implements UserListAdapter.OnClickListener {
private FragmentAdminUserListBinding binding;
private AdminUserListViewModel adminListViewModel;
private UserListAdapter userListAdapter;
private FirebaseAuth auth = FirebaseAuth.getInstance();
public AdminUserListFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binding = FragmentAdminUserListBinding.inflate(inflater, container, false);
final View v = binding.getRoot();
// Gets ViewModel instance to observe its LiveData
binding.setModel(adminListViewModel);
adminListViewModel = ViewModelProviders.of(getActivity()).get(AdminUserListViewModel.class);
adminListViewModel.init();
adminListViewModel.getUsers().observe(this, new Observer<FirestoreRecyclerOptions<User>>() {
@Override
public void onChanged(@Nullable FirestoreRecyclerOptions<User> users) {
initRecyclerView(users);
userListAdapter.startListening();
}
});
adminListViewModel.getIsUpdating().observe(this, new Observer<Boolean>() {
@Override
public void onChanged(@Nullable Boolean aBoolean) {
if (!aBoolean) {
binding.rvUser.smoothScrollToPosition(adminListViewModel.getUsers().getValue().getSnapshots().size() - 1);
}
}
});
return v;
}
private void initRecyclerView(FirestoreRecyclerOptions<User> users) {
userListAdapter = new UserListAdapter(users);
binding.rvUser.setAdapter(userListAdapter);
binding.rvUser.setHasFixedSize(true);
binding.rvUser.setLayoutManager(new LinearLayoutManager(getContext()));
}
@Override
public void onStart() {
super.onStart();
}
public void onStop() {
super.onStop();
userListAdapter.stopListening();
}
public void onItemClick() {
Log.d("plum", "click");
}
}
UserListViewModel:
public class AdminUserListViewModel extends ViewModel {
private MutableLiveData<FirestoreRecyclerOptions<User>> users = new MutableLiveData<>();
private FirestoreRepository repo;
private MutableLiveData<Boolean> isUpdating = new MutableLiveData<>();
public void init() {
repo = FirestoreRepository.getInstance();
users.setValue(repo.getUsersFromRepo());
}
public MutableLiveData<FirestoreRecyclerOptions<User>> getUsers() {
return users;
}
public MutableLiveData<Boolean> getIsUpdating() {
return isUpdating;
}
}
UserListAdapter:
public class UserListAdapter extends FirestoreRecyclerAdapter<User, UserListAdapter.UserViewHolder> {
User currentUser = new User();
// Listens for a Firestore query
public UserListAdapter(@NonNull FirestoreRecyclerOptions<User> options) {
super(options);
}
@NonNull
@Override
public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RvuserItemBinding binding = RvuserItemBinding.inflate(layoutInflater, parent, false);
return new UserViewHolder(binding);
}
// UserViewHolder is the class that defines the views that hold the User data
class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private RvuserItemBinding binding;
OnClickListener onClickListener;
public UserViewHolder(@NonNull RvuserItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(User user) {
binding.setUser(user);
binding.executePendingBindings();
}
public void onClick(View v) {
onClickListener.onItemClick();
}
}
@Override
public void onBindViewHolder(@NonNull UserViewHolder holder, int position, User user) {
holder.bind(user);
}
public interface OnClickListener{
void onItemClick();
}
}
frag_admin_user_list xml:
<layout xmlns:bind="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="...viewmodels.AdminUserListViewModel" />
</data>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_admin_list"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvUser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
tools:listitem="@layout/rvuser_item" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
rvuser_item xml:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<import type="android.view.View"/>
<variable
name="user"
type="...models.User"/>
<variable
name="fragment"
type="...fragments.AdminUserListFragment" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/rvuser_item"
android:background="@android:color/holo_orange_light"
android:clickable="true"
android:onClick="@{()->fragment.onItemClick()}">
<TextView
android:id="@+id/tvClientName"
style="@style/user_title"
android:text="@{user.clientName}"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvEmail"
android:text="@{user.email}"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
Спасибо!