如何使用SwipeRefreshLayout刷新此应用?

时间:2016-11-03 23:21:45

标签: java json android-studio

我正在关注如何在制作图库的教程,我想使用SwipeRefreshLayout来更新图片,但实际上我不知道如何。这是代码我该如何解决它?

MainActivity.java
package info.androidhive.glide.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;  
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import info.androidhive.glide.R;
import info.androidhive.glide.adapter.GalleryAdapter;
import info.androidhive.glide.app.AppController;
import info.androidhive.glide.model.Image;

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint =         "http://url.com/examp.php";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);

RecyclerView.LayoutManager mLayoutManager = new   GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);

/* recyclerView.addOnItemTouchListener(new    GalleryAdapter.RecyclerTouchListener(getApplicationContext(), 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 =   getSupportFragmentManager().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("Downloading json...");
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();
                        image.setName(object.getString("name"));

                        JSONObject url = object.getJSONObject("url");
                        image.setSmall(url.getString("small"));
                        image.setMedium(url.getString("medium"));
                        image.setLarge(url.getString("large"));
                        image.setTimestamp(object.getString("timestamp"));

                        images.add(image);

                    } catch (JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                    }
                }

                mAdapter.notifyDataSetChanged();
            }
        }, 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);
}
}

并且继承了activity_main.xml

Activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

1 个答案:

答案 0 :(得分:0)

这是一个非常好的例子,解释了如何Swipe to Refresh

您必须将整个xml包装在@Override public void onMapLoaded() { try { LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); Location getLastLocation = locationManager.getLastKnownLocation (LocationManager.PASSIVE_PROVIDER); try { if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2 * 1000, 5, this); } if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2 * 1000, 5, this); } } catch (SecurityException ex) { ex.printStackTrace(); } } catch (NullPointerException | SecurityException ex) { ex.printStackTrace(); } } @Override public void onLocationChanged(Location location) { LatLng objLatLng = new LatLng(location.getLatitude(), location.getLongitude()); marker = map.addMarker(new MarkerOptions().position(objLatLng)); } 中。初始化android.support.v4.widget.SwipeRefreshLayout中的SwipeRefreshLayout,为其添加一个监听器,并在其方法中添加:onCreate您可以调用您的方法:onRefresh()

请勿忘记在网络请求结束的方法中使用fetchImages();,以便刷新知道何时停止。