Я пытаюсь загрузить изображение по умолчанию из нарисованного на случай, если Glide не может подключиться к серверу и получить изображения.я использую фрагмент с адаптером.
вот мой фрагмент:
public class PhotosFragment extends Fragment {
private OnFragmentInteractionListener mListener;
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
protected RecyclerView recyclerView;
private TextView titreDemo;
....
....
....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_photos, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentPhotoInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentPhotoInteraction(Uri uri);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
recyclerView = getView().findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(getContext());
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getContext(), images);
titreDemo = getView().findViewById(R.id.titre_demo);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getContext(), recyclerView, new GalleryAdapter.ClickListener() {
@Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
@Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
private void fetchImages() {
pDialog.setMessage(getContext().getResources().getString(R.string.loading) + " ...");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTag(url.getString("tag"));
if(getArguments() != null && getArguments().getString(DATA_RECEIVE) != null && !getArguments().getString(DATA_RECEIVE).isEmpty()){
if(getArguments().getString(DATA_RECEIVE).equals(image.getTag())) {
images.add(image);
}
}else{
images.add(image);
}
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
if(images != null && !images.isEmpty()) {
if(getArguments() != null && getArguments().getString(DATA_TITRE) != null) {
titreDemo.setText(getArguments().getString(DATA_TITRE));
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage(getResources().getString(R.string.photo_non_dispo))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getFragmentManager().popBackStackImmediate();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
и вот мой адаптер:
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
private List<Image> images;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
}
}
public GalleryAdapter(Context context, List<Image> images) {
mContext = context;
this.images = images;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallery_thumbnail, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = images.get(position);
if(image != null && image.getMedium() != null) {
Glide.with(mContext).load(image.getMedium()).load(image.getLarge()).thumbnail(0.5f).transition(DrawableTransitionOptions.withCrossFade()).apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate().centerCrop().dontTransform()).into(holder.thumbnail);
}else{
Log.e("gallerie adapter", "inside onBindViewHolder");
Glide.with(mContext).load(R.drawable.building).load(R.drawable.building).thumbnail(0.5f).transition(DrawableTransitionOptions.withCrossFade()).apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate().centerCrop().dontTransform()).into(holder.thumbnail);
}
}
@Override
public int getItemCount() {
return images.size();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private GalleryAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
как я могу отобразить некоторую картинкуиз моего drawables в случае загрузки с удаленного сервера не удалось?как видите, я позвонил mAdapter.notifyDataSetChanged();
в onErrorResponse
, чтобы войти в адаптер, но он не работает.Каков наилучший способ достичь этого?