2017-09-02 93 views
0

我在我的活動中有RecyclerView的片段,但每當我開始片段時,RecyclerView已經滾動到底部。要加載更多的項目,用戶必須向上滾動一些,然後滾動回到底部,並且當更多的項目加載時,RecyclerView再次滾動到新的底部。當活動開始時,RecyclerView已經滾動到底部

這裏是片段中的代碼。

public class FavouriteFragment extends Fragment{ 

public RecyclerView recyclerView ; 
public RecyclerView.Adapter adapter ; 
public LinearLayoutManager layoutManager ; 

int pastVisiblesItems, visibleItemCount, totalItemCount; 

Constants constants; 
ArrayList<CardSetterGetter> arrayList; 
private List<CardSetterGetter> imagelist; 
int start ; 
public int end ; 
boolean loading = true ; 
int totalcount ; 
ArrayList<String> imageNameArray ; 
String androidId; 
String categoryName ; 
String cateGoryFlag = "false"; 
String url; 
String tagname = ""; 

ArrayList<String> title ; 
ProgressBar progressBar ; 

TextView errormsg ; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //to hide search 
    setHasOptionsMenu(true); 
} 
@Override 
public void onPrepareOptionsMenu(Menu menu) { 
    MenuItem item = menu.findItem(R.id.search); 
    item.setVisible(false); 
} 



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

    View view = inflater.inflate(R.layout.favourite_fragment,container,false); 

    arrayList = new ArrayList<CardSetterGetter>(); 
    imageNameArray = new ArrayList<String>(); 
    start = 0; 
    end = start + 2 ; 

    imagelist = new ArrayList<CardSetterGetter>(); 

    recyclerView = (RecyclerView)view.findViewById(R.id.recyclerview); 
    progressBar = (ProgressBar)view.findViewById(R.id.progressBar); 
    errormsg = (TextView) view.findViewById(R.id.error); 

    getdata(); 

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { 
     @Override 
     public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 
      if(dy > 0) 
      { 
       visibleItemCount = layoutManager.getChildCount(); 
       totalItemCount = layoutManager.getItemCount(); 
       pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); 
       int i = visibleItemCount + pastVisiblesItems ; 
       System.out.println(i); 
       System.out.println(totalItemCount); 

       if(loading) { 
        if (i == totalItemCount) { 
         loading = false ; 
         start = arrayList.size() ; 
         end = arrayList.size() + 2 ; 
         requestWithSomeHttpHeaders2(start,end); 
         new Handler().postDelayed(new Runnable() { // This thread runs in the UI 
          @Override 
          public void run() { 
           loading = true; 
          } 
         },2000); 
        } 
       } 
      } 
     } 
    }); 
    requestWithSomeHttpHeaders2(start, end); 

    return view ; 
} 

public void requestWithSomeHttpHeaders2(int s , int e) { 
    RequestQueue queue = Volley.newRequestQueue(getActivity()); 

    url = "my url"; 

    StringRequest postRequest = new StringRequest(Request.Method.GET, url , 
      new Response.Listener<String>() 
      { 
       @Override 
       public void onResponse(String response) { 
        try { 
         progressBar.setVisibility(View.GONE); 
         JSONObject jsonObject = new JSONObject(response); 
         JSONArray payload = jsonObject.getJSONArray("Payload"); 
         JSONObject MetaData = jsonObject.getJSONObject("MetaData"); 
         System.out.println(response); 
         totalcount = MetaData.getInt("TotalCount"); 
         System.out.println("200" + " " + totalcount); 
         System.out.println("payload length"+payload.length()); 

         int i ; 
         for(i =0 ; i < payload.length() ; i++) 
         { 

          System.out.println(payload.getJSONObject(i).getString("image_title")); 
          System.out.println(payload.getJSONObject(i).getString("image_title")); 
          System.out.println(payload.getJSONObject(i).getString("image_file")); 
          System.out.println(payload.getJSONObject(i).getString("image_description")); 
          System.out.println(payload.getJSONObject(i).getString("image_category")); 
          System.out.println(payload.getJSONObject(i).getString("image_tags")); 
          System.out.println(payload.getJSONObject(i).getString("id")); 
          System.out.println(payload.getJSONObject(i).getString("favourite")); 

          String newString = payload.getJSONObject(i).getString("image_file").replace("original_image", "thumbnail"); 
          CardSetterGetter all = new CardSetterGetter(payload.getJSONObject(i).getString("image_file"), 
            payload.getJSONObject(i).getString("image_title"), 
            payload.getJSONObject(i).getString("image_description"), 
            payload.getJSONObject(i).getString("image_category"), 
            payload.getJSONObject(i).getString("image_tags"), 
            payload.getJSONObject(i).getString("id"), 
            payload.getJSONObject(i).getString("favourite")); 

          System.out.println("i value is " + i); 

          arrayList.add(all); 
          Handler handler = new Handler(); 

          final Runnable r = new Runnable() { 
           public void run() { 
            adapter = new RecyclerViewAdapter(getActivity(),arrayList,imageNameArray,totalItemCount); 
            recyclerView.setHasFixedSize(true); 
            layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); 
            recyclerView.setLayoutManager(layoutManager); 
            recyclerView.setAdapter(adapter); 
            adapter.notifyDataSetChanged(); 
            //adapter.notifyItemInserted(arrayList.size() - 1); 
            if (end >= totalcount) 
            { 
             int index = totalcount -1 ; 
             recyclerView.scrollToPosition(index); 
            } 
            else { 
             recyclerView.scrollToPosition(end); 
            } 
           } 
          }; 

          handler.post(r); 

         } 

        } catch (Exception e) { 
         e.printStackTrace(); 
         System.out.println("error" + e); 

        } 

       } 

      }, 


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


        // TODO Auto-generated method stub 
        Log.d("ERROR","error => "+error.toString()); 
        // definitions.setText("check your internet connection"); 
        NetworkResponse networkResponse = error.networkResponse; 
//      Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode); 
        if (networkResponse != null) { 
         Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode); 
        } 

        if (error instanceof TimeoutError) { 
         Log.e("Volley", "TimeoutError"); 
        }else if(error instanceof NoConnectionError){ 
         Log.e("Volley", "NoConnectionError"); 
        } else if (error instanceof AuthFailureError) { 
         Log.e("Volley", "AuthFailureError"); 
        } else if (error instanceof ServerError) { 
         Log.e("Volley", "ServerError"); 
        } else if (error instanceof NetworkError) { 
         Log.e("Volley", "NetworkError"); 
        } else if (error instanceof ParseError) { 
         Log.e("Volley", "ParseError"); 
        } 
       } 

      } 

    ); 

    queue.add(postRequest); 

} 
public void getdata(){ 
    try { 
     SharedPreferences sharedPref = getActivity().getSharedPreferences("mobileId" , Context.MODE_PRIVATE); 
     androidId = sharedPref.getString("mobileId" , ""); 
     sharedPref = getActivity().getSharedPreferences("categoryInfo" , Context.MODE_PRIVATE); 
     categoryName = sharedPref.getString("categoryName" , ""); 
     cateGoryFlag = sharedPref.getString("categoryFlag" , ""); 
     tagname = sharedPref.getString("tagname" , ""); 

    }catch (Exception e){ 

    } 


} 
} 

我試着刪除,如果代碼的else部分,但取得了recyclerView滾動每當用戶到達recyclerView底部的頂部。

請告訴我,如果您需要更多的代碼或代碼RecyclerViewAdapter

+0

您是否嘗試過使用其他經理構造函數:LinearLayoutManager(activity,orientation,reverseLayout)?如果我沒有記錯,我有一個類似的問題與RecyclerView,我通過設置佈局方向(垂直或水平,無論您需要)來解決它。 –

+0

@EdoardoArnaudo不,我沒有嘗試過。我不知道該怎麼做。你能發表一個答案解釋更多關於它 –

回答

0

我通過向佈局管理器提供正確的方向解決了類似的問題。我想你的代碼更改爲類似:

public RecyclerView.Adapter adapter ; 
adapter = new RecyclerViewAdapter(getActivity(),arrayList,imageNameArray,totalItemCount); 
recyclerView.setHasFixedSize(true); 

//This line should do the trick: 
//first parameter is the context 
//second parameter is the orientation 
//third parameter is used for reverse layout (if you need to show items from last to first) 
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); 
recyclerView.setLayoutManager(layoutManager); 
recyclerView.setAdapter(adapter); 

//probably better to use notifyDataSetChanged to let the adapter know you just initialized it (instead of notifying a single element) 
adapter.notifyDataSetChanged(); 

不知道爲什麼你提供總項目數的適配器爲好,但是這是問題的範圍,肯定不會給任何問題。

編輯: 現在您發佈的整個片段代碼,我看到至少幾個問題: - 在RecyclerView初始化不應該在一個可運行的,但在onCreateView或部分啓動功能。你只需要設置管理器和適配器一次。 - 您向適配器提供了imageNameArray,但您要在其中插入新項目?如果你希望你的RecyclerView向下滾動到最後插入的項目,你首先需要一個項目在該位置添加到ArrayList,然後通知插入,這樣的事情:

int position = imageNameAray.size(); 
imageNameArray.add(item); 
adapter.notifyItemInserted(position); //this makes the view update the item in that position, making the recycler to scroll there 
+0

謝謝你的幫助,但沒有奏效。 recyclerView的行爲與更改之前的行爲完全相同。即使他們沒有任何區別,我是否應該保留這些變化? –

+0

是的,最好明確佈局方向!也許它可以幫助你從片段中提供更多的代碼,例如:你在哪裏初始化recyclerView,如何獲取數據......只使用該片段可能不夠。旁註:儘可能避免手動調用scrollToPosition,如果配置正確,回收站應該正常運行。 –

+0

立即檢查代碼。我添加了整個片段的代碼。 –

相關問題