RecyclerView简单实现预加载(笔记)

添加依赖

compile 'com.android.support:recyclerview-v7:25.1.0'
compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.3'

注:

本篇使用的adapter是使用了github上的开源框架
使用方法可以自已查阅[这里写链接内容](https://github.com/CymChad/BaseRecyclerViewAdapterHelper)

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:id="@+id/activity_main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kevinyang.demo1.MainActivity">

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

</LinearLayout>

MainActivity主功能实现

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private List<String> mDataList;
    private MySimpleAdapter mAdapter;
    private boolean isLoadingMore = false;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);

        mDataList = new ArrayList<>();

        //模拟数据
        for (int i = 0; i < 20; i++) {
            mDataList.add(""+i);
        }

        mLinearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);

        mAdapter = new MySimpleAdapter(R.layout.item_view,mDataList);
        mRecyclerView.setAdapter(mAdapter);

        //添加滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                Log.e(TAG, "onScrolled: dx"+dx+"---dy"+dy );

                int lastVisibleItem = ((LinearLayoutManager) mLinearLayoutManager).findLastVisibleItemPosition();
                int totalItemCount = mLinearLayoutManager.getItemCount();//总条目
                //lastVisibleItem >= totalItemCount - 5 表示剩下5个item实现预加载
                // dy>0 表示向下滑动,滑动距离
                if (lastVisibleItem >= totalItemCount - 5 && dy > 0) {

                    if(isLoadingMore){
                        Toast.makeText(getApplicationContext(), "已经预加载了!", Toast.LENGTH_SHORT).show();
                    } else{
                        LoadMore();//加载更多
                    }
                    isLoadingMore = !isLoadingMore;
                }
            }
        });



    }

    //模拟加载更多数据
    private void LoadMore() {
        for (int i = 0; i < 20; i++) {
            mDataList.add(""+i);
        }
        mAdapter.notifyDataSetChanged();
    }
}

adapter的条目布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/icon"
        android:src="@mipmap/ic_launcher"
        android:layout_width="48dp"
        android:layout_height="48dp"/>

    <TextView
        android:gravity="center"
        android:layout_gravity="center_vertical"
        android:id="@+id/name"
        android:text="111111111111111111111"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

adapter的简单实现

public class MySimpleAdapter extends BaseQuickAdapter<String,BaseViewHolder>{
    public MySimpleAdapter(int layoutResId, List<String> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, String item) {
        helper.setText(R.id.name,item);
    }
}

总结

可以看出RecyclerView的预加载很简单的就实现了,主要就是获取当前条目,在一个自定义的预定的范围,判断是都超过来实现加载.
发布了8 篇原创文章 · 获赞 1 · 访问量 1万+
展开阅读全文

RecyclerView初始化时加载了全部item,导致打开页面卡顿问题

01-29

一个选择城市的页面,打开页面时就初始化了全部item,之后怎么滑动也不会再调用onBindViewHolder方法。下面是适配器代码,求解谢谢! ``` public class SelectCityRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; private final int TYPE_LETTER = 0; private final int TYPE_CHINESE = 1; private final int TYPE_HEADER = 2; private SelectCityContract.OnSelectCityListener mListener; private String mLetters[] = {"#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; private int mLetterPos[] = new int[27]; SelectCityRvAdapter(Context context){ mContext = context; mListener = (SelectCityContract.OnSelectCityListener) context; getAllLetterPos(); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = null; if(viewType == TYPE_LETTER){ view = LayoutInflater.from(mContext).inflate(R.layout.item_select_city_letter,parent, false); return new ViewHolderLetter(view); }else if(viewType == TYPE_CHINESE){ view = LayoutInflater.from(mContext).inflate(R.layout.item_select_city_chinese,parent, false); return new ViewHolderCity(view); } return null; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) { if(holder instanceof ViewHolderLetter){ ((ViewHolderLetter)holder).textView.setText(City.citys[position]); for(int i=0;i<mLetterPos.length;i++){ if(mLetterPos[i] == position){ mListener.onScrollLetter(i); } } }else if(holder instanceof ViewHolderCity){ ((ViewHolderCity)holder).textView.setText(City.citys[position]); ((ViewHolderCity)holder).textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mListener.onSelect(City.citys[position]); } }); } KLog.i("aaa","第"+position+"项"); } @Override public int getItemCount() { return City.citys.length; } @Override public int getItemViewType(int position) { Pattern pattern = Pattern.compile("^[A-Z]"); if (pattern.matcher(City.citys[position]).matches()){ return TYPE_LETTER; }else{ return TYPE_CHINESE; } } public int[] getLetterPos(){ return mLetterPos; } private void getAllLetterPos(){ ThreadPoolUtils.getInstance().execute(new Runnable() { @Override public void run() { for(int n=0;n<mLetters.length;n++){ boolean exits = false; for(int i=0;i<City.citys.length;i++){ if(City.citys[i].equals(mLetters[n])){ mLetterPos[n] = i; exits = true; break; } } if(!exits){ if(n == 0){ mLetterPos[0] = 0; }else{ mLetterPos[n] = mLetterPos[n - 1]; } } } } }); } public class ViewHolderCity extends RecyclerView.ViewHolder{ TextView textView; public ViewHolderCity(View itemView) { super(itemView); textView = itemView.findViewById(R.id.textView); } } public class ViewHolderLetter extends RecyclerView.ViewHolder{ TextView textView; public ViewHolderLetter(View itemView) { super(itemView); textView = itemView.findViewById(R.id.textView); } } }![图片说明](https://img-ask.csdn.net/upload/201901/29/1548743089_581308.png) ``` 问答

为什么在fragment里面放的RecyclerView 没写加载会自动加载出来?

06-30

直接上代码 把加载fragment写在监听里可是程序一运行就已经显示了 package com.example.bmvod.fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private GalleryAdapter mAdapter; private List<Integer> mDatas; private FirstFragment firstFragment; private SecondFragment secondFragment; // private ThirdFragment thirdFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initDatas(); mRecyclerView = (RecyclerView) findViewById(R.id.recid1); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(linearLayoutManager); mAdapter = new GalleryAdapter(this, mDatas); mAdapter.setOnItemClickLitener(new GalleryAdapter.OnItemClickLitener() { @Override public void onItemClick(View view, int position) { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); switch (position) { case 0: firstFragment = new FirstFragment(); transaction.add(R.id.fragment, firstFragment); hideAllFragments(transaction); transaction.show(firstFragment); break; case 1: secondFragment = new SecondFragment(); transaction.add(R.id.fragment, secondFragment); hideAllFragments(transaction); transaction.show(secondFragment); break; } transaction.commit(); } }); mRecyclerView.setAdapter(mAdapter); } private void hideAllFragments(FragmentTransaction ft) { if (firstFragment != null) { ft.hide(firstFragment); } if (secondFragment != null) { ft.hide(secondFragment); } } private void initDatas() { mDatas = new ArrayList<Integer>(Arrays.asList(R.drawable.bottom1, R.drawable.bottom2, R.drawable.bottom3, R.drawable.bottom4, R.drawable.bottom5, R.drawable.bottom1, R.drawable.bottom2, R.drawable.bottom3, R.drawable.bottom4)); } private void setDefaultFragment() { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); firstFragment = new FirstFragment(); transaction.replace(R.id.fragment, firstFragment); transaction.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` ``` package com.example.bmvod.fragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; 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 java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by bmvod on 2016/6/29. */ public class FirstFragment extends Fragment { private RecyclerView mRecyclerView; private GalleryAdapter2 mAdapter; private List<Integer> mDatas; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.firstfragmentlayout, container, false); initDatas2(); mRecyclerView = (RecyclerView) view.findViewById(R.id.fragmengrecv1); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(linearLayoutManager); mAdapter = new GalleryAdapter2(getActivity(), mDatas); mRecyclerView.setAdapter(mAdapter); return view; } private void initDatas2() { mDatas = new ArrayList<Integer>(Arrays.asList(R.drawable.smalltop1, R.drawable.smalltop2, R.drawable.smalltop3, R.drawable.smalltop4, R.drawable.smalltop5, R.drawable.smalltop1, R.drawable.smalltop2, R.drawable.smalltop3, R.drawable.smalltop4)); } } ``` ``` 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览