应该将什么上下文名称传递给 Glide 方法?

What context name should be passed to Glide method?

为了在使用 viewholderfragment 时加载图像,我不知道应该传递的上下文对象名称。下面是我的滑行代码:

Glide.with(activity).load(cheeses.getImageView()).fitCenter().into(mImageView);

错误:

at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1555) 
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:667)
at com.bumptech.glide.manager.RequestManagerRetriever.getSupportRequestManagerFragment(RequestManagerRetriever.java:187)
at com.bumptech.glide.manager.RequestManagerRetriever.supportFragmentGet(RequestManagerRetriever.java:195)
at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:104)
at com.bumptech.glide.Glide.with(Glide.java:644)
at com.support.android.designlibdemo.ViewHolderClass.ViewHolder.bindToCheese(ViewHolder.java:42)
at com.support.android.designlibdemo.CheeseListFragment.populateViewHolder(CheeseListFragment.java:112)
at com.support.android.designlibdemo.CheeseListFragment.populateViewHolder(CheeseListFragment.java:93)

在 ViewHolder 中使用 getActivity,而不是 MainActivity mainActvity;

问题在这里:

 Glide.with(activity)

您正在创建一个新的 Activity,而不是获取当前的 activity,这就是您收到该错误的原因。你应该这样做:

 Glide.with(getActivity())...

理想情况下,您可以将片段上下文传递到您的 RecyclerView,并在调用中使用该上下文。文件说:

public static RequestManager with(Context context)

Begin a load with Glide by passing in a context. Any requests started using a context will only have the application level options applied and will not be started or stopped based on lifecycle events. In general, loads should be started at the level the result will be used in. If the resource will be used in a view in a child fragment, the load should be started with with(android.app.Fragment)} using that child fragment. Similarly, if the resource will be used in a view in the parent fragment, the load should be started with with(android.app.Fragment) using the parent fragment. In the same vein, if the resource will be used in a view in an activity, the load should be started with with(android.app.Activity)}.

This method is appropriate for resources that will be used outside of the normal fragment or activity lifecycle (For example in services, or for notification thumbnails).

Parameters: context - Any context, will not be retained. Returns: A RequestManager for the top level application that can be used to start a load.

Source

你可以这样做:

public ViewHolder(View view, Context context) {
    super(view);
    mView = view;
    mImageView = (ImageView) view.findViewById(R.id.avatar);
    mTextView = (TextView) view.findViewById(android.R.id.text1);
    activity = context;
}

那么你可以使用 activity.