recyclerView.setOnScrollChangeListener 不工作

Posted

技术标签:

【中文标题】recyclerView.setOnScrollChangeListener 不工作【英文标题】:recyclerView.setOnScrollChangeListener not working 【发布时间】:2018-04-26 02:56:09 【问题描述】:

这是我的片段代码。 我将此代码用于无尽的回收器视图,当滚动回收器视图项时从服务器获取数据。但代码不起作用。在此代码 recyclerView.setOnScrollChangeListener() 不起作用它显示错误视图不能应用于 android.content .context。 滚动列表时如何使用片段中的setOnScrollChangeListener从服务器加载数据。

    public class Fragment1 extends Fragment implements 
    RecyclerView.OnScrollChangeListener
    //Creating a List of superheroes
     private List<SuperHero> listSuperHeroes;

     //Creating Views
     private RecyclerView recyclerView;
     private RecyclerView.LayoutManager layoutManager;
     private RecyclerView.Adapter adapter;
     public ProgressBar progressBar;

     //Volley Request Queue
      private RequestQueue requestQueue;

       //The request counter to send ?page=1, ?page=2  requests
       private int requestCount = 1;

       public Fragment1() 

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

        

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup 
        container, Bundle savedInstanceState) 
         // Inflate the layout for this fragment
         View view= inflater.inflate(R.layout.activity_main, container, 
       false);
       //Initializing Views
       recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(getActivity());

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
 progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    return view;


//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) 
    //Initializing ProgressBar


    //Displaying Progressbar
   // progressBar.setVisibility(View.VISIBLE);
    //setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() 
                @Override
                public void onResponse(JSONArray response) 
                    //Calling method parseData to parse the json response

                    Log.e("response",response.toString());
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                
            ,
            new Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                
            );

    //Returning the request
    return jsonArrayRequest;


//This method will get data from the web api
private void getData() 
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;


//This method will parse json data
private void parseData(JSONArray array) 
    for (int i = 0; i < array.length(); i++) 
        //Creating the superhero object
        //int a= array.length();
        //String s=String.valueOf(a);
        //Log.e("array",s);
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try 
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            //superHero.setName(json.getString(Config.TAG_NAME));
            //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            superHero.setMglId(json.getString(Config.TAG_MGLID));
            superHero.setAgeHeight(json.getString(Config.TAG_AGEHEIGHT));
            superHero.setCommunity(json.getString(Config.TAG_COMMUNITY));
            superHero.setOccupation(json.getString(Config.TAG_OCCUPATION));
            superHero.setIncome(json.getString(Config.TAG_INCOME));
         catch (JSONException e) 
            e.printStackTrace();
        
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();


//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) 
    if (recyclerView.getAdapter().getItemCount() != 0) 
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    
    return false;


//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) 
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) 
        //Calling the method getdata again
        getData();
    

【问题讨论】:

【参考方案1】:

使用这个

recyclerView.setOnScrollChangeListener(Fragment1.this);

而不是这个

recyclerView.setOnScrollChangeListener(getActivity());

编辑

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) 
                super.onScrolled(recyclerView, dx, dy);
                if (isLastItemDisplaying(recyclerView)) 
                  //Calling the method getdata again
                   getData();
                
            
        );

【讨论】:

先生如何消除recycler view item之间的间隙 你能分享你的 recyclerview 项目和布局的代码吗?我可以帮你@user6734679 @user6734679 让你的 RelativeLayoutandroid:layout_height="wrap_content" @user6734679 很乐意帮助您享受编码的乐趣 先生,回收站视图在 23 以下不起作用这是我的代码链接pastebin.com/0KqYUwXv【参考方案2】:

请改用recyclerView.addOnScrollListener(onScrollListener);

RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() 
 @Override
 public void onScrollStateChanged(RecyclerView recyclerView, int newState) 
      super.onScrollStateChanged(recyclerView, newState);
 

 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) 
      super.onScrolled(recyclerView, dx, dy);
 

【讨论】:

addOnScrollListener 已弃用

以上是关于recyclerView.setOnScrollChangeListener 不工作的主要内容,如果未能解决你的问题,请参考以下文章