如何将碎片的上下文转换为LifecycleOwner?

我有以下方案。我有一个活动,里面有一个片段。在这段代码中,我显示了来自后端数据库的一些记录。我还使用了如下所示的适配器:

public class MovieAdapter extends PagedListAdapter<Movie, MovieAdapter.MovieViewHolder> {
    private Context context;

    public MovieAdapter(Context context) {this.context = context;}

    @NonNull
    @Override
    public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //Create the view
    }

    @Override
    public void onBindViewHolder(@NonNull final MovieViewHolder holder, int position) {
        Movie movie = getItem(position);
        String title = movie.title;
        holder.titleTextView.setText(title);

        MovieRepository movieRepository = new MovieRepository(context);
        LiveData<Movie> liveData = movieRepository.retrieveFavoriteMovie(movie.id);
        liveData.observe(context, m -> { //Error
            if(m != null) {
                boolean favorite = m.favorite;
                if(favorite) {
                    //Do something
                } else {
                    //Do something else
                }
            }
        });
    }

    class MovieViewHolder extends RecyclerView.ViewHolder {
        ImageView favoriteImageView;
        TextView titleTextView;

        MovieViewHolder(View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.title_text_view);                favoriteImageView = itemView.findViewById(R.id.favorite_image_view);
        }
    }
}

onBindViewHolder中,我尝试检查ROMM数据库中是否存在特定电影,但收到以下错误:

Wrong 1st argument type. Found: 'android.content.Context', required: 'android.arch.lifecycle.LifecycleOwner'

那么如何将片段的上下文转换为LifecycleOwner,以便我可以像在我的方法的参数中一样使用它呢?


解决方案

android.content.Context不实现android.arch.lifecycle.LifecycleOwner

您必须传递AppCompatActivity的实例,该实例实现android.arch.lifecycle.LifecycleOwner(或执行该操作的任何其他类)。

或CAST(AppCompatActivity) context,当contextinstanceofAppCompatActivity时。要可靠地从上下文获取活动,请选中https://stackoverflow.com/a/46205896/2413303

相关文章