6

您好我有一個選項卡式的活動,並在第一個選項卡我從服務器獲取數據,並顯示在卡視圖回收站查看。爲了從服務器獲取數據,我使用了抽象庫。我想實現Pull來刷新以加載數據(所以無論何時我需要向網絡發送請求)。我還想禁用網絡請求,每當我切換選項卡(因爲當我改變我的應用程序中的選項卡焦點它開始提取數據)我想做網絡請求只有一次(當用戶登錄第一次),然後其他請求只能通過拉來刷新。拉刷新recyclerview android

這裏是我的片段,我已經recyclerview和顯示數據:

public class Tab1History extends Fragment 
{ 

private RecyclerView recyclerView; 
private CespiteAdapter adapter; 
UserSessionManager session; 

private static final String URL_DATA = "http://mydata.php"; 

private List<CespiteOgg> cespiteOggList; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) 
{ 

    View rootView = inflater.inflate(R.layout.tab1history, container, false); 

    recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view); 
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size 
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); 

    cespiteOggList = new ArrayList<>(); 

    loadRecyclerViewData(); 

      return rootView; 
} 

private void loadRecyclerViewData() 
{ 
    // Session class instance 
    session = new UserSessionManager(getActivity()); 
    //get user data from session 
    HashMap<String, String> user = session.getUserDetails(); 
    //get name 
    String name = user.get(UserSessionManager.KEY_NAME); 
    // get username 
    final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME); 

    final ProgressDialog progressDialog = new ProgressDialog(getActivity()); 
    progressDialog.setMessage("Carimento dati..."); 
    progressDialog.show(); 

    StringRequest stringRequest = new StringRequest(Request.Method.POST, 
      URL_DATA, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String s) { 
        progressDialog.dismiss(); 
        try { 
         JSONObject jsonObject = new JSONObject(s); 
         JSONArray array = jsonObject.getJSONArray("dates"); 

         for(int i=0; i<array.length(); i++) 
         { 
          JSONObject o = array.getJSONObject(i); 
          CespiteOgg item = new CespiteOgg(
            o.getString("CodNumInventario"), 
            o.getString("Nome"), 
            o.getString("DtCatalogazione"), 
            o.getString("CodIdA"), 
            o.getString("username") 
          ); 
          cespiteOggList.add(item); 
         } 

         adapter = new CespiteAdapter(cespiteOggList, getActivity()); 
         recyclerView.setAdapter(adapter); 

        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        progressDialog.dismiss(); 
       } 
      }) 
      { 
       @Override 
       protected Map<String, String> getParams() throws AuthFailureError { 
        Map<String, String> params = new HashMap<String, String>(); 
        params.put("Username", usernameUtente); 
        return params; 
       } 
      }; 

    RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest); 

} 
} 

而且它的適配器:

public class CespiteAdapter extends RecyclerView.Adapter<CespiteAdapter.ViewHolder> 
{ 


private List<CespiteOgg> cespiteOggList; 
private Context context; 

public CespiteAdapter(List<CespiteOgg> cespiteOggList, Context context) { 

    this.cespiteOggList = cespiteOggList; 
    this.context = context; 
} 

public class ViewHolder extends RecyclerView.ViewHolder 
{ 

    public CardView cv; 
    public TextView txtNumInventario; 
    public TextView txtNomeCespite; 
    public TextView txtDtCatalogazione; 
    public TextView txtAula; 
    public TextView txtNomeUser; 


    ViewHolder(View itemView) 
    { 

     super (itemView); 
     //cv = (CardView) itemView.findViewById(R.id.cardView); 
     txtNumInventario = (TextView) itemView.findViewById(R.id.txtNumeroInventario); 
     txtNomeCespite = (TextView) itemView.findViewById(R.id.txtNomeCespite); 
     txtDtCatalogazione = (TextView) itemView.findViewById(R.id.txtDataCatalogazione); 
     txtAula = (TextView) itemView.findViewById(R.id.txtAula); 
     txtNomeUser= (TextView) itemView.findViewById(R.id.txtNomeUser); 


    } 
} 



@Override 
public CespiteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
{ 

    LayoutInflater inflater = LayoutInflater.from(parent.getContext()); 

    View cespiteView = inflater.inflate(R.layout.cespite_card_view, parent, false); 

    return new ViewHolder(cespiteView); 
} 

@Override 
public void onBindViewHolder(ViewHolder holder, int position) 
{ 

    CespiteOgg cespiteOgg = cespiteOggList.get(position); 

    holder.txtNumInventario.setText(cespiteOgg.getNumInventario()); 
    holder.txtNomeCespite.setText(cespiteOgg.getNomeCespite()); 
    holder.txtDtCatalogazione.setText(cespiteOgg.getDtCatalogazione()); 
    holder.txtAula.setText(cespiteOgg.getAula()); 
    holder.txtNomeUser.setText(cespiteOgg.getNomeUser()); 

} 

@Override 
public int getItemCount() 
{ 

    return cespiteOggList.size(); 
} 

} 
+0

檢查此鏈接https://developer.android.com/培訓/滑動/添加碰擦,interfa ce.html –

回答

15

你可以用它代替ProgressDialog機器人SwipeRefreshLayout部件。

按照以下步驟在您的Tab1history片段整合SwipeRefreshLayout

1.在佈局tab1history,添加SwipeRefreshLayout爲根佈局,並把RecyclewrView裏面。

// tab1history.xml 
<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.SwipeRefreshLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/swipe_container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

     <android.support.v7.widget.RecyclerView 
      android:id="@+id/my_recycler_view" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 

</android.support.v4.widget.SwipeRefreshLayout> 

2.在你Tab1History片段,使用SwipeRefreshLayout如下從服務器加載數據:

// Tab1History.java 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.widget.SwipeRefreshLayout; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import com.android.volley.Request; 
import com.android.volley.Response; 
import com.android.volley.toolbox.StringRequest; 

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

import java.util.ArrayList; 


public class Tab1History extends Fragment implements SwipeRefreshLayout.OnRefreshListener { 

    SwipeRefreshLayout mSwipeRefreshLayout; 
    private RecyclerView recyclerView; 
    private CespiteAdapter adapter; 
    UserSessionManager session; 

    private static final String URL_DATA = "http://mydata.php"; 

    private List<CespiteOgg> cespiteOggList; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) 
    { 

     View rootView = inflater.inflate(R.layout.tab1history, container, false); 


     recyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view); 
     recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size 
     recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); 

     cespiteOggList = new ArrayList<>(); 


     // SwipeRefreshLayout 
     mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container); 
     mSwipeRefreshLayout.setOnRefreshListener(this); 
     mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, 
       android.R.color.holo_green_dark, 
       android.R.color.holo_orange_dark, 
       android.R.color.holo_blue_dark); 

     /** 
     * Showing Swipe Refresh animation on activity create 
     * As animation won't start on onCreate, post runnable is used 
     */ 
     mSwipeRefreshLayout.post(new Runnable() { 

      @Override 
      public void run() { 

       mSwipeRefreshLayout.setRefreshing(true); 

       // Fetching data from server 
       loadRecyclerViewData(); 
      } 
     }); 

     return rootView; 
    } 

    /** 
    * This method is called when swipe refresh is pulled down 
    */ 
    @Override 
    public void onRefresh() { 

     // Fetching data from server 
     loadRecyclerViewData(); 
    } 

    private void loadRecyclerViewData() 
    { 
     // Showing refresh animation before making http call 
     mSwipeRefreshLayout.setRefreshing(true); 

     // Session class instance 
     session = new UserSessionManager(getActivity()); 
     //get user data from session 
     HashMap<String, String> user = session.getUserDetails(); 
     //get name 
     String name = user.get(UserSessionManager.KEY_NAME); 
     // get username 
     final String usernameUtente = user.get(UserSessionManager.KEY_USERNAME); 


     StringRequest stringRequest = new StringRequest(Request.Method.POST, 
       URL_DATA, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String s) { 

         try { 
          JSONObject jsonObject = new JSONObject(s); 
          JSONArray array = jsonObject.getJSONArray("dates"); 

          for(int i=0; i<array.length(); i++) 
          { 
           JSONObject o = array.getJSONObject(i); 
           CespiteOgg item = new CespiteOgg(
             o.getString("CodNumInventario"), 
             o.getString("Nome"), 
             o.getString("DtCatalogazione"), 
             o.getString("CodIdA"), 
             o.getString("username") 
           ); 
           cespiteOggList.add(item); 
          } 

          adapter = new CespiteAdapter(cespiteOggList, getActivity()); 
          recyclerView.setAdapter(adapter); 

         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 

         // Stopping swipe refresh 
         mSwipeRefreshLayout.setRefreshing(false); 

        } 
       }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 

         // Stopping swipe refresh 
         mSwipeRefreshLayout.setRefreshing(false); 
        } 
       }) 
     { 
      @Override 
      protected Map<String, String> getParams() throws AuthFailureError { 
       Map<String, String> params = new HashMap<String, String>(); 
       params.put("Username", usernameUtente); 
       return params; 
      } 
     }; 

     RegisterRequest.getmInstance(getActivity()).addToRequestque(stringRequest); 

    } 
} 

希望這將正常工作。

+0

謝謝你,作品像一個魅力! – arst3k

0

拉到刷新列表查看&在Android Studio中的RecyclerView示例 - SwipeRefreshLayout.I希望此代碼正常工作,您可以嘗試此代碼。

基本拉來刷新/ SwipeRefreshLayout XML代碼:

​​

下面你可以通過基本的拉步驟說明下載代碼,請參閱最後輸出和步驟要刷新的例子。得到充分的代碼示例http://abhiandroid.com/materialdesign/pulltorefresh

0

源代碼

https://drive.google.com/open?id=1qjJ_to-1knVNaJB4T3U_L_p_YYNvgAeZ

APK

https://drive.google.com/open?id=1MxQZwjIXgR2jgDkUW1mbFrTLMSaQQisC

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { 


    SwipeRefreshLayout mSwipeRefreshLayout; 


     // SwipeRefreshLayout 
     mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); 

     mSwipeRefreshLayout.setOnRefreshListener(this); 
//  mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, 
     mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, 
       android.R.color.holo_green_dark, 
       android.R.color.holo_orange_dark, 
       android.R.color.holo_blue_dark); 

     /** 
     * Showing Swipe Refresh animation on activity create 
     * As animation won't start on onCreate, post runnable is used 
     */ 
     mSwipeRefreshLayout.post(new Runnable() { 

      @Override 
      public void run() { 

       if(mSwipeRefreshLayout != null) { 
        mSwipeRefreshLayout.setRefreshing(true); 
       } 
       // TODO Fetching data from server 
       fetchContacts(); 
      } 
     }); 



    @Override 
    public void onRefresh() { 
     fetchContacts(); 
    }