主要注意的点
自动轮播+手动+home键之后页面onResume接着轮播+下拉刷新轮播图一起刷新
下拉刷新的时候遇到了bug:下拉刷新之后不再自动,小白点也不动,图片也不轮播了
修复:需要重新设置recycleview的adapter,因为轮播图是作为recycleview的header存在的
public class FiveActivity extends AutoLayoutActivity implements BaseQuickAdapter.RequestLoadMoreListener {
FiveActivityBinding binding;
private int page = 1;
private int pagesize = 10;
public static final String TAG = "FourActivity";
private BannerBean bannerBean;
private ViewPager viewPager;
private TextView textView;
private LinearLayout pointLl;
private RotateVpAdapter vpAdapter;
private int mAllPage;
private StudyHomeAdapter mThirdLevelAdapter;
private List<StudyHomeBean.DataBean.ListBean> mList = new ArrayList<>();
private boolean isLoad;
private int nowIndex;
private static final int TIME = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_five);
initdata();
}
private void initdata() {
**下拉刷新的时候重新设置一下recyclerView的adapter,因为轮播图是作为recycle的头部加载的**
/** Explain : 初始化下拉刷新
* @author LiXaing create at 2017/7/22 21:56*/
binding.refresh.setBackgroundColor(0XFFFFFFFF);
binding.refresh.setColorSchemeColors(Color.parseColor("#4158B0"));
binding.refresh.setProgressViewOffset(true, 0, 100);
binding.refresh.setRefreshing(false);
binding.refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
binding.refresh.setRefreshing(true);//当前是测试效果,正式用的时候,当前要设置为true
**handler.removeCallbacks(rotateRunnable);**
RefreshingList();
}
});
/** Explain : 列表初始化
* @author ZhangYu create at 2018/1/19 0019 */
mThirdLevelAdapter = new StudyHomeAdapter(R.layout.item_study_home, null);
LinearLayoutManager layoutManager3 = new LinearLayoutManager(this);
layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
mThirdLevelAdapter.setOnLoadMoreListener(this);
binding.recyclerView.setLayoutManager(layoutManager3);
//如果Item高度固定 增加该属性能够提高效率
binding.recyclerView.setHasFixedSize(true);
binding.recyclerView.setAdapter(mThirdLevelAdapter);
LoadData();
}
@Override
public void onResume() {
super.onResume();
//**当页面重现的时候,remove掉之前auto的runnable。延迟将由这次决定**
isRotate = true;
if(rotateRunnable!=null&&handler!=null) {
handler.removeCallbacks(rotateRunnable);
handler.postDelayed(rotateRunnable, TIME);
}
}
@Override
protected void onPause() {
super.onPause();
**//暂停的时候,remove掉之前auto的runnable**
isRotate=false;
if(rotateRunnable!=null&&handler!=null) {
handler.removeCallbacks(rotateRunnable);
}
}
private void LoadData() {
if (page == 1 && (null == binding.refresh || !binding.refresh.isRefreshing())) {
binding.loadingProgress.showLoading();
}
OkHttpUtils
.post()
.url(NetWorkURLBean.STUDY_HOME_URL)
.addParams("page", String.valueOf(page))
.addParams("pagesize", String.valueOf(pagesize))
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
LogUtil.e(TAG, "onError====" + e.getMessage());
if (binding.refresh != null) {
binding.refresh.setRefreshing(false);
}
if (binding.loadingProgress != null) {
showError();
}
}
@Override
public void onResponse(String response, int id) {
LogUtil.e(TAG, "onResponse response====" + response);
processResponse2(response);
}
});
}
private void LoadBanner() {
OkHttpUtils
.post()
.url(NetWorkURLBean.STUDY_HEAD_URL)
.addParams("page", String.valueOf(page))
.addParams("pagesize", String.valueOf(pagesize))
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
LogUtil.e(TAG, "onError====" + e.getMessage());
}
@Override
public void onResponse(String response, int id) {
LogUtil.e(TAG, "onResponse response====" + response);
processResponse3(response);
}
});
}
/**
* Explain : 处理列表 **可以替换成自己封装的网络请求方法**
*
* @author Hyh create at 2018/10/16
*/
private void processResponse2(String response) {
StudyHomeBean findBean = new Gson().fromJson(response, StudyHomeBean.class);
String code = findBean.getCode();
if ("200".equals(code)) {
List<StudyHomeBean.DataBean.ListBean> list = findBean.getData().getList();
if (page == 1 && mList.size() != 0) {
mList.clear();
}
if (page == 1) {
**//加载轮播图**
LoadBanner();
}
if (null != list && list.size() > 0) {
mList.addAll(list);
}
mAllPage = findBean.getData().getAll_page();
LogUtil.e(TAG, "mAllPage----" + mAllPage);
/**
* Explain:加载更多数据处理
*/
if (isLoad) {
//当前页下雨于总页数,添加数据,可以加载更多
if (page < mAllPage) {
mThirdLevelAdapter.notifyDataChangedAfterLoadMore(list, true);
//当前页等总页数,添加数据,不可以加载更多
} else if (page == mAllPage) {
mThirdLevelAdapter.notifyDataChangedAfterLoadMore(list, false);
showLoadCompleteAllData();
//其他情况就展示没有更多数据
} else {
showLoadCompleteAllData();
}
/**
* Explain:首次加载或下拉刷新数据处理
*/
} else {
//没有数据,展示空界面
if (null == list || list.size() == 0) {
showEmpty();
//有数据,进行判断展示
} else {
binding.loadingProgress.showContent();
mThirdLevelAdapter.setNewData(list);//新增数据
//共1页,展示没有更多数据
if (mAllPage == 1) {
showLoadCompleteAllData();
//大于一页,只展示数据
} else {
mThirdLevelAdapter.openLoadMore(pagesize, true);//设置是否可以下拉加载 以及加载条数
}
}
}
}
}
/**
* Explain : 处理轮播图
*
* @author Hyh create at 2018/10/16
*/
private void processResponse3(String response) {
bannerBean = new Gson().fromJson(response, BannerBean.class);
View inflate = View.inflate(this, R.layout.item_study_head, null);
viewPager = (ViewPager) inflate.findViewById(R.id.rotate_vp);
pointLl = (LinearLayout) inflate.findViewById(R.id.rotate_point_container);
textView = (TextView) inflate.findViewById(R.id.item_tv);
if (bannerBean.getData().size() >= 0) {
textView.setText(bannerBean.getData().get(0).getTitle());
}
vpAdapter = new RotateVpAdapter(bannerBean.getData(), this, textView);
viewPager.setAdapter(vpAdapter);
vpAdapter.notifyDataSetChanged();
// ViewPager的页数为int最大值,设置当前页多一些,可以上来就向前滑动
// 为了保证第一页始终为数据的第0条 取余要为0,因此设置数据集合大小的倍数
viewPager.setCurrentItem(bannerBean.getData().size() * 100);
// mThirdLevelAdapter.notifyDataSetChanged();
// 开始轮播
handler = new Handler();
startRotate();
// 添加轮播小点
addPoints();
// 随着轮播改变小点
changePoints();
mThirdLevelAdapter.addHeaderView(inflate);
}
//========================================轮播设置
private Handler handler;
private boolean isRotate = false;
private Runnable rotateRunnable;
private void changePoints() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (isRotate) {
// 把所有小点设置为白色
for (int i = 0; i < bannerBean.getData().size(); i++) {
ImageView pointIv = (ImageView) pointLl.getChildAt(i);
pointIv.setImageResource(R.drawable.point_white);
}
// 设置当前位置小点为灰色
ImageView iv = (ImageView) pointLl.getChildAt(position % bannerBean.getData().size());
iv.setImageResource(R.drawable.point_grey);
textView.setText(bannerBean.getData().get(position % bannerBean.getData().size()).getTitle());
**//当有手动操作时,remove掉之前auto的runnable。延迟将由手动的这次决定。**
handler.removeCallbacks(rotateRunnable);
handler.postDelayed(rotateRunnable, TIME);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* 添加轮播切换小点
*/
private void addPoints() {
// 有多少张图加载多少个小点
for (int i = 0; i < bannerBean.getData().size(); i++) {
ImageView pointIv = new ImageView(this);
pointIv.setPadding(5,5,5,5);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20,20);
pointIv.setLayoutParams(params);
// 设置第0页小点的为灰色
if (i == 0) {
pointIv.setImageResource(R.drawable.point_grey);
} else {
pointIv.setImageResource(R.drawable.point_white);
}
pointLl.addView(pointIv);
}
}
/**
* 开始轮播
*/
private void startRotate() {
rotateRunnable = new Runnable() {
@Override
public void run() {
nowIndex = viewPager.getCurrentItem();
viewPager.setCurrentItem(++nowIndex);
if (isRotate) {
handler.postDelayed(rotateRunnable, TIME);
}
}
};
handler.postDelayed(rotateRunnable, TIME);
}
@Override
public void onLoadMoreRequested() {
if (page <= mAllPage) {
page++;
System.out.println("onLoadMoreRequested");
}
LoadData();
isLoad = true;
}
/**
* Explain : 加载完所有数据后展示
*
* @author LianHaiLin
* create at 19:31
*/
private void showLoadCompleteAllData() {
//所有数据加载完成后显示
ToastUtil.showToast(this, "已经全部加载");
}
/**
* Explain: 展示界面为空
*
* @author LianHaiLin
* create at 23:23
*/
private void showEmpty() {
binding.loadingProgress.showEmpty(this.getResources().getDrawable(R.drawable.load_no_data), "暂无数据", "");
}
//网络请求错误
private void showError() {
binding.loadingProgress.showError(this.getResources().getDrawable(R.drawable.jc_error_normal), "网络异常", "请检查网络后重试", "重新访问", new View.OnClickListener() {
@Override
public void onClick(View v) {
initdata();
}
});
}
//刷新的方法
private void RefreshingList() {
page = 1;
isLoad = false;
initdata();
}
}
public class RotateVpAdapter extends PagerAdapter {
private List<BannerBean.DataBean> datas;
private Context context;
private LayoutInflater inflater;
private TextView textView;
public RotateVpAdapter(List<BannerBean.DataBean> datas, Context context, TextView textView) {
this.datas = datas;
this.context = context;
this.textView = textView;
inflater = LayoutInflater.from(context);
}
public RotateVpAdapter(List<BannerBean.DataBean> data, Context context) {
this.context = context;
inflater = LayoutInflater.from(context);
}
public void setDatas(List<BannerBean.DataBean> datas) {
this.datas = datas;
notifyDataSetChanged();
}
@Override
public int getCount() {
// 为了让ViewPager到最后一页不会像翻书一样回到第一页
// 设置页数为int最大值,这样向下滑动永远都是下一页
return datas == null ? 0 : Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
// position是int最大值所以这里可能是几百甚至上千,因此取余避免数组越界
int newPosition = position % datas.size();
View convertView = inflater.inflate(R.layout.item_vp, container, false);
ImageView imageView = (ImageView) convertView.findViewById(R.id.item_iv);
Glide.with(context)
.load(datas.get(newPosition).getImage_url())
.into(imageView);
如果View已经在之前添加到了一个父组件,则必须先remove,否则会抛出IllegalStateException。
ViewParent viewParent = convertView.getParent();
if (viewParent != null) {
ViewGroup parent = (ViewGroup) viewParent;
parent.removeView(convertView);
}
container.addView(convertView);
return convertView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
布局文件
item_study_head
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="334px">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="334px">
<android.support.v4.view.ViewPager
android:id="@+id/rotate_vp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="@+id/rotate_point_container"
android:layout_width="match_parent"
android:layout_height="50px"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom|center"
android:background="#5f000000"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="20px"/>
<TextView
android:id="@+id/item_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom|right"
android:layout_marginBottom="6px"
android:layout_marginRight="20px"
android:text=""
android:textColor="#fff"
android:textSize="30px"/>
</RelativeLayout>
</RelativeLayout>
item_vp
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="324px">
<ImageView
android:id="@+id/item_iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitXY" />
</RelativeLayout>
从项目中抽取部分代码,不便上传源码