在片段中使用网络图像视图 - android studio

Using NetworkImageView in fragments - androidstudio

我正在尝试使用 volley 库以片段形式下载图像。但我无法修复错误:

public static class ViewFragment extends Fragment {

        ImageLoader mImageLoader;
        NetworkImageView mNetworkImageView;
        private static String IMAGE_URL =
                "http://meteo.profi-net.sk/webcams/BIELAPUT-l.jpg";

        public ViewFragment() {
            // Required empty public constructor
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Get the NetworkImageView that will display the image.
            mNetworkImageView = (NetworkImageView) getView().findViewById(R.id.networkImageView);

            // Get the ImageLoader through your singleton class.
            mImageLoader = VolleySingleton.getInstance(this).getImageLoader();  //!!!!!! HERE IS THE ERROR

            // Set the URL of the image that should be loaded into this view, and
            // specify the ImageLoader that will be used to make the request.
            mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_camera_view, container, false);
        }


    }

getInstance(this) 被标记为错误,但我不知道如何更改它。如果我在某些 activity.

中编写完全相同的代码,它会起作用

有人可以解释一下如何在片段中使用 NetworkImageView 吗?

getInstance 需要一个 Context 作为参数,Fragment 不需要,但 Activity 需要。 Fragment 可以通过调用 getActivity 方法访问其持有的 activity。您应该在每次调用之前检查该片段是否仍附加到其 activity 否则您将崩溃

所以你可以这样做:

if(isAdded())
{
            .......... your code ..............
            // Get the ImageLoader through your singleton class.
            mImageLoader = VolleySingleton.getInstance(getActivity()).getImageLoader();
                .......... your code ..............
}