我正在使用 MVVM 架构模型创建一个应用程序。我在 MainActivity 中有回收器视图,单击回收器视图项目中的删除按钮时,它应该从房间数据库中删除。我知道可以在适配器类中删除项目,但因为我正在使用MVVM模型我想在Repository类中进行删除操作。
这是我的代码如下:
UserDao.java
@Dao
public interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void Insert(User... users);
@Query("SELECT * FROM Users")
LiveData<List<User>> getRoomUsers();
@Delete
void Delete(User... user);
}
UserAdapter.java
public class UserAdapter extends
RecyclerView.Adapter<UserAdapter.ViewHolder> {
List<User> userList;
Context context;
public UserAdapter(List<User> userList, Context context) {
this.userList = userList;
this.context = context;
}
@NonNull
@Override
public UserAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull UserAdapter.ViewHolder holder, int position) {
final User users = userList.get(position);
holder.row_name.setText(users.getName());
holder.row_age.setText(users.getAge());
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
@Override
public int getItemCount() {
return userList.size();
}
public void setUserList(List<User> userList) {
this.userList = userList;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView row_name,row_age;
ImageView delete;
public ViewHolder(@NonNull View itemView) {
super(itemView);
row_name = itemView.findViewById(R.id.row_name);
row_age = itemView.findViewById(R.id.row_age);
delete = itemView.findViewById(R.id.delete);
}
}
}
倚天杖
胡子哥哥
相关分类