RecycleView结合banner
主页面
public class HomeFragment extends Fragment {
private RecyclerView recycle;
private ArrayList banners;
private ArrayList articles;
private Gson gson;
private String bannerUrl = "https://www.wanandroid.com/banner/json";
private String articleUrl = "https://www.wanandroid.com/article/list/";
private int page = 0;
private HomeAdapter homeAdapter;
private SmartRefreshLayout sl;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
gson = new GsonBuilder().create();
initView(view);
initData();
return view;
}
private void initView(View view) {
// 创建适配器
recycle = view.findViewById(R.id.recycle);
banners = new ArrayList<>();
articles = new ArrayList<>();
homeAdapter = new HomeAdapter(banners, articles, getActivity());
// 绑定适配器
recycle.setAdapter(homeAdapter);
// 获取布局管理器
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
// 设置recycle的方向
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
// 设置布局管理器
recycle.setLayoutManager(linearLayoutManager);
// 设置分割线
recycle.addItemDecoration(new DividerItemDecoration(getActivity(), OrientationHelper.VERTICAL));
// 刷新
sl = view.findViewById(R.id.sl);
//监听
sl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
@Override
public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
page++;
initData();
}
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
page = 0;
if (articles != null && articles.size() > 0) {
articles.clear();
initData();
}
}
});
}
private void initData() {
new Thread(new Runnable() {
@Override
public void run() {
// 获得GSON字符串
String bannerGson = getResponse(bannerUrl);
Log.e("TAG", bannerGson);
String articleGson = getResponse(articleUrl + page + "/json");
// 获得数组
final BannerBean bannerBean = gson.fromJson(bannerGson, BannerBean.class);
final ArticleBean articleBean = gson.fromJson(articleGson, ArticleBean.class);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// 添加到空集合
banners.addAll(bannerBean.getData());
articles.addAll(articleBean.getData().getDatas());
// 刷新适配器
homeAdapter.notifyDataSetChanged();
//
sl.finishLoadMore();
sl.finishRefresh();
}
});
}
// 从网络获取字符串
private String getResponse(String urls) {
try {
URL url = new URL(urls);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
byte[] bytes = new byte[1024];
int length = 0;
StringBuffer buffer = new StringBuffer();
InputStream inputStream = connection.getInputStream();
while ((length = inputStream.read(bytes)) != -1) {
buffer.append(new String(bytes, 0, length));
}
return buffer.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}).start();
}
}
适配器
public class RC_Adapter extends RecyclerView.Adapter {
private ArrayList banners;
private ArrayList article;
private LayoutInflater inflater;
private Context context;
// 定义多布局
//注意:如果有banner,banner必须为0
private static final int TYPE_1 = 0;
private static final int TYPE_2 = 1;
public RC_Adapter(ArrayList banners, ArrayList article, Context context) {
this.banners = banners;
this.article = article;
this.context = context;
this.inflater = LayoutInflater.from(context);
}
//判断不同的条目布局
@Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_1;
} else {
return TYPE_2;
}
}
// 创建不同的条目布局
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_1:
View view1 = inflater.inflate(R.layout.layout_typeone, null);
return new ViewHolder1(view1);
case TYPE_2:
View view2 = inflater.inflate(R.layout.layout_typetwo, null);
return new ViewHolder2(view2);
}
return null;
}
//绑定布局
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
//banner布局
case TYPE_1:
ViewHolder1 viewHolder1 = (ViewHolder1) holder;
viewHolder1.banner.setImages(banners).setImageLoader(new ImageLoader() {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
BannerBean.DataBean dataBean = (BannerBean.DataBean) path;
Glide.with(context).load(dataBean.getImagePath()).into(imageView);
}
}).start();
break;
//条目布局
case TYPE_2:
ArticleBean.DataBean.DatasBean datasBean = article.get(position - 1);
ViewHolder2 viewHolder2 = (ViewHolder2) holder;
viewHolder2.tv_title.setText(datasBean.getTitle());
viewHolder2.tv_time.setText(datasBean.getNiceDate());
break;
}
}
// 确定条目数量
@Override
public int getItemCount() {
//因为有banner所以总数量要+1
return article.size() + 1;
}
public static
class ViewHolder1 extends RecyclerView.ViewHolder {
public View rootView;
public Banner banner;
public ViewHolder1(View rootView) {
super(rootView);
this.rootView = rootView;
this.banner = (Banner) rootView.findViewById(R.id.banner);
}
}
public static
class ViewHolder2 extends RecyclerView.ViewHolder{
public View rootView;
public TextView tv_title;
public TextView tv_time;
public ViewHolder2 (View rootView) {
super(rootView);
this.rootView = rootView;
this.tv_title = (TextView) rootView.findViewById(R.id.tv_title);
this.tv_time = (TextView) rootView.findViewById(R.id.tv_time);
}
}
}
RecycleView多布局
主页 面
/**
* RecyclerView使用步骤
* 1.添加依赖(版本问题注意)
* 2.创建布局(宽高必须是充满的)
* 3.找控件
* 4.设置布局管理器(三种显示方式:线性布局、网格布局、瀑布流布局)
* 5.获取数据(切换子线程的方法)
* 6.创建适配器(*****)-- 重写三个,通过接口回调实现点击事件
* 7.设置适配器
*/
public class MainActivity extends AppCompatActivity {
private RecyclerView rv;
private String foodUrl = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=";
private ArrayList list;
// private RvAdapter adapter;
private MultiLayoutAdapter adapter;
private int page = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
initListenr();
}
private void initListenr() {
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
/**
* 滑动状态改变
* @param recyclerView
* @param newState
*/
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.e("TAG", "MainActivity onScrollStateChanged()" + newState);
//获取布局管理
LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
//获取最后最后一页最后条目的索引
int lastVisibleItemPosition = lm.findLastVisibleItemPosition();
int firstVisibleItemPosition = lm.findFirstVisibleItemPosition();
//获取总共的题目个数
int itemCount = recyclerView.getAdapter().getItemCount();
//获取当前页条目个数
int childCount = recyclerView.getChildCount();
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE:
if (itemCount > 0 && itemCount == childCount + firstVisibleItemPosition) {
page++;
initData();
}
break;
}
}
/**
* 滑动监听
* @param recyclerView
* @param dx
* @param dy
*/
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.e("TAG", "MainActivity onScrolled(),dx:" + dx + ",dy:" + dy);
}
});
}
private void initData() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(foodUrl + page);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = con.getInputStream();
String response = streamToString(inputStream);
FoodBean foodBean = new Gson().fromJson(response, FoodBean.class);
final List data = foodBean.getData();
runOnUiThread(new Runnable() {
@Override
public void run() {
list.addAll(data);
adapter.notifyDataSetChanged();
}
});
}
//获取banners集合
//banners.addAll(bannner);
//adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private String streamToString(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int length = -1;
byte[] bytes = new byte[1024];
try {
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
}
outputStream.close();
String result = outputStream.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
private void initView() {
rv = (RecyclerView) findViewById(R.id.rv);
//获取布局管理器并设置
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
StaggeredGridLayoutManager staggeredManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
// linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
rv.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
//分割线
rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
//创建适配器
// adapter = new RvAdapter(list, this);
adapter = new MultiLayoutAdapter(list, this);
//设置适配器
rv.setAdapter(adapter);
}
}
适配器
/**
* 多布局适配器写法:
* 1.自定义一个适配器继承自RecyclerView.Adapter,泛型是
* 2.多(相对于单布局)重写一个方法getItemViewType(),条目view分类型
* 3.重写onCreateViewHolder,分类型加载不同布局
* 4.重写onBindViewHolder,根据holder获取类型,然后分类型赋值
*/
class MultiLayoutAdapter extends RecyclerView.Adapter {
private ArrayList list;
private ArrayList banners;
private Context context;
// 定义不同的布局
private int VIEW_ITEM_TYPE_ONE = 1;
private int VIEW_ITEM_TYPE_TWO = 2;
private int VIEW_ITEM_TYPE_THREE = 3;
public MultiLayoutAdapter(ArrayList list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_ITEM_TYPE_ONE) {
View view = LayoutInflater.from(context).inflate(R.layout.item_rv_one, null);
return new ViewHolderOne(view);
} else if (viewType == VIEW_ITEM_TYPE_TWO) {
View view = LayoutInflater.from(context).inflate(R.layout.item_rv_two, null);
return new ViewHolderTwo(view);
} else {
View view = LayoutInflater.from(context).inflate(R.layout.item_rv_two, null);
return new ViewHolderTwo(view);
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
FoodBean.DataBean dataBean = list.get(position);
int itemViewType = holder.getItemViewType();
if (itemViewType == VIEW_ITEM_TYPE_ONE) {
//banners,position==0
ViewHolderOne viewHolderOne = (ViewHolderOne) holder;
viewHolderOne.tv_item.setText(dataBean.getTitle());
Glide.with(context).load(dataBean.getPic()).into(viewHolderOne.iv_item);
} else if (itemViewType == VIEW_ITEM_TYPE_TWO) {
int newPosition = position - 1;//position==1
FoodBean.DataBean dataBean1 = list.get(newPosition);
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
viewHolderTwo.tv_item.setText(dataBean.getTitle());
Glide.with(context).load(dataBean.getPic()).into(viewHolderTwo.iv_item);
} else {
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
viewHolderTwo.tv_item.setText(dataBean.getTitle());
Glide.with(context).load(dataBean.getPic()).into(viewHolderTwo.iv_item);
}
}
//判断返回不同的条目
@Override
public int getItemViewType(int position) {
int i = position % 3;
if (i == 0) {
return VIEW_ITEM_TYPE_ONE;
} else if (i == 1) {
return VIEW_ITEM_TYPE_TWO;
} else {
return VIEW_ITEM_TYPE_THREE;
}
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolderOne extends RecyclerView.ViewHolder {
private ImageView iv_item;
private TextView tv_item;
public ViewHolderOne(@NonNull View itemView) {
super(itemView);
iv_item = itemView.findViewById(R.id.iv_item);
tv_item = itemView.findViewById(R.id.tv_item);
}
}
public class ViewHolderTwo extends RecyclerView.ViewHolder {
private ImageView iv_item;
private TextView tv_item;
public ViewHolderTwo(@NonNull View itemView) {
super(itemView);
iv_item = itemView.findViewById(R.id.iv_item);
tv_item = itemView.findViewById(R.id.tv_item);
}
}
}
实现翻页加载
recycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE && buttom) {
page++;
iniData();
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager layoutManager = (LinearLayoutManager) rv_fragmnetintent.getLayoutManager();
int itemCount = layoutManager.getItemCount();
int childCount = layoutManager.getChildCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (firstVisibleItemPosition + childCount == itemCount && itemCount > 0) {
buttom = true;
} else {
buttom = false;
}
}
});