第一步:网络权限
第二步:依赖:
implementation 'com.youth.banner:banner:1.4.9'
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okhttp3:okhttp:3.7.0'
implementation 'com.jcodecraeer:xrecyclerview:1.5.9'
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'com.github.bumptech.glide:annotations:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '27.1.1'
}
}
}
}
第三步:布局:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".v.MainActivity"
android:orientation="vertical">
<com.youth.banner.Banner
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:id="@+id/banner_id"></com.youth.banner.Banner>
<com.jcodecraeer.xrecyclerview.XRecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="6"
android:id="@+id/xRecyclerView_id"></com.jcodecraeer.xrecyclerview.XRecyclerView>
</LinearLayout>
layout_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:layout_width="100dp"
android:layout_height="160dp"
android:id="@+id/image_id"
android:scaleType="fitXY"
android:src="@mipmap/ic_launcher"
android:layout_marginRight="20dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="160dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name_id"
android:text="1111111"
android:layout_alignParentTop="true"
android:layout_margin="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/summary_id"
android:text="1111111"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:layout_below="@+id/name_id"/>
</RelativeLayout>
</LinearLayout>
layout_item2:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="160dp"
android:id="@+id/image_id2"
android:scaleType="fitXY"
android:src="@mipmap/ic_launcher"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="160dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name_id2"
android:text="1111111"
android:layout_alignParentLeft="true"
android:layout_margin="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/summary_id2"
android:text="1111111"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
android:layout_below="@+id/name_id2"/>
</RelativeLayout>
</LinearLayout>
layout_item3:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/name_id3"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="160dp"
android:id="@+id/image_id3"
android:src="@mipmap/ic_launcher"/>
</LinearLayout>
第四步:主方法
custom:
public interface MyInterface {
public interface ModelInterface{
//
public void toGetRequest(String url, Map<String,String> map, MyModel.MyCallBack myCallBack);
}
public interface PresenterInterface{
//调用Model层传递数据
public void toModel(int page,int count);
//释放内存
public void onDestroy();
}
public interface ViewInterface{
public void reFreDisplay(Object obj);
}
}
工具类:
public class OkHttpUtil {
static OkHttpUtil okHttpUtil;
OkHttpClient okHttpClient;
private OkHttpUtil(){
okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response proceed = chain.proceed(request);
return proceed;
}
}).build();
}
public static synchronized OkHttpUtil getStance(){
if (okHttpUtil == null){
okHttpUtil = new OkHttpUtil();
}
return okHttpUtil;
}
public void doGet(String url, final Map<String,String> map, final Handler handler){
if (map != null && map.size() > 0){
StringBuilder builder = new StringBuilder();
for (String key : map.keySet()){
String value = map.get(key);
builder.append(key).append("=").append(value).append("&");
}
String string = builder.toString();
int i = string.lastIndexOf("&");
string = string.substring(0,i);
url = url + "?" + string;
}
Request request = new Request.Builder().url(url).get().build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Message message = new Message();
message.obj = json;
handler.sendMessage(message);
}
});
}
}
外部缓存类:
@GlideModule
public class GlideCache extends AppGlideModule {
@Override
public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
super.applyOptions(context, builder);
String path = getStorageDirectory() + "/clidCache";
Log.e("tag" ,"path = " + path );
int diskCacheSizeBytes = 1024 * 1024 * 100; // 100 MB
builder.setDiskCache(new DiskLruCacheFactory(path ,diskCacheSizeBytes));
}
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
super.registerComponents(context, glide, registry);
Log.e("tag" ,"registerComponents" );
}
//外部路径
private String sdRootPath = Environment.getExternalStorageDirectory().getPath();
private String appRootPath = null;
private String getStorageDirectory(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ? sdRootPath : appRootPath;
}
}
缓存异常类:
public class CrashHandler implements Thread.UncaughtExceptionHandler{
Thread.UncaughtExceptionHandler exceptionHandler;
static CrashHandler crashHandler;
private CrashHandler(){
}
public static synchronized CrashHandler getInstance(){
if (crashHandler == null){
crashHandler = new CrashHandler();
}
return crashHandler;
}
Context context;
public void init(Context context){
this.context = context;
exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
//将此类设为默认异常处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, final Throwable e) {
new Thread(){//在主线程中弹出
@Override
public void run() {
super.run();
Looper.prepare();
Toast.makeText(context,"捕获到异常 = "+e.getMessage(),Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
}
}
m层:
public class MyModel implements MyInterface.ModelInterface {
MyCallBack myCallBack;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String json = (String) msg.obj;
Gson gson = new Gson();
MyBean bean = gson.fromJson(json,MyBean.class);
myCallBack.success(bean);
}
};
@Override
public void toGetRequest(String url, Map<String, String> map, MyCallBack myCallBack) {
this.myCallBack = myCallBack;
OkHttpUtil.getStance().doGet(url,map,handler);
}
public interface MyCallBack {
public void success(Object obj);
}
}
p层:
public class MyPresenter<T> implements MyInterface.PresenterInterface {
MyInterface.ViewInterface viewInterface;
MyInterface.ModelInterface modelInterface;
T tt;
public MyPresenter(T tt) {
modelInterface = new MyModel();
viewInterface = (MyInterface.ViewInterface) tt;
this.tt = tt;
}
@Override
public void toModel(int page, int count) {
String dataUrl = "http://172.17.8.100/movieApi/movie/v1/findHotMovieList";
Map<String,String> map = new HashMap<>();
map.put("page",page+"");
map.put("count",count+"");
modelInterface.toGetRequest(dataUrl, map, new MyModel.MyCallBack() {
@Override
public void success(Object obj) {
viewInterface.reFreDisplay(obj);
}
});
}
@Override
public void onDestroy() {
if (viewInterface != null){
viewInterface = null;
}
}
}
v层:MainActivity
public class MainActivity extends AppCompatActivity implements MyInterface.ViewInterface{
List<MyBean.ResultBean> list = new ArrayList<>();
XRecyclerView xRecyclerView;
MyInterface.PresenterInterface presenterInterface;
MyAdapter adapter;
int page = 1;
int count = 2;
Banner banner;
List<String> bList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xRecyclerView = findViewById(R.id.xRecyclerView_id);
banner = findViewById(R.id.banner_id);
presenterInterface = new MyPresenter<>(this);
init();
bList.add("http://172.17.8.100/images/movie/stills/ws/ws1.jpg");
bList.add("http://172.17.8.100/images/movie/stills/jhen/jhen1.jpg");
bList.add("http://172.17.8.100/images/movie/stills/dzd6qmwj/dzd6qmwj1.jpg");
setBanner();
}
private void setBanner() {
banner.isAutoPlay(true).setDelayTime(1000)
.setImages(bList)
.setImageLoader(new ImageLoader() {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
}).start();
}
private void init() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
xRecyclerView.setLayoutManager(layoutManager);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
adapter = new MyAdapter(list,this);
xRecyclerView.setAdapter(adapter);
presenterInterface.toModel(page,count);
xRecyclerView.setLoadingMoreEnabled(true);
xRecyclerView.setPullRefreshEnabled(true);
xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
page++;
presenterInterface.toModel(page,count);
xRecyclerView.refreshComplete();
}
@Override
public void onLoadMore() {
count += count;
presenterInterface.toModel(page,count);
xRecyclerView.loadMoreComplete();
}
});
adapter.setOnItemClickListener(new MyAdapter.ItemClickListener() {
@Override
public void onItemClick(int i) {
Toast.makeText(MainActivity.this,list.get(i).getName(),Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void reFreDisplay(Object obj) {
MyBean bean = (MyBean) obj;
list.addAll(bean.getResult());
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
presenterInterface.onDestroy();
presenterInterface = null;
}
}
bean类:
package com.bawei.lianxi.bean;
import java.util.List;
public class MyBean {
private String message;
private String statuis;
private List<ResultBean> result;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatuis() {
return statuis;
}
public void setStatuis(String statuis) {
this.statuis = statuis;
}
public List<ResultBean> getResult() {
return result;
}
public void setResult(List<ResultBean> result) {
this.result = result;
}
public static class ResultBean{
private String imageUrl;
private String name;
private String summary;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
}
适配器:
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<MyBean.ResultBean> list;
Context context;
//声明自定义的接口
ItemClickListener itemClickListener;
public interface ItemClickListener{
public void onItemClick(int i);
}
public void setOnItemClickListener(ItemClickListener listener){
this.itemClickListener = listener;
}
public MyAdapter(List<MyBean.ResultBean> list,Context context){
this.list = list;
this.context = context;
}
@Override
public int getItemViewType(int position) {
return position%3;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder;
View view;
if (getItemViewType(viewType) == 0){
view = LayoutInflater.from(context).inflate(R.layout.layout_item,null);
holder = new ViewHolder1(view);
}else if (getItemViewType(viewType) == 1){
view = LayoutInflater.from(context).inflate(R.layout.layout_item3,null);
holder = new ViewHolder3(view);
}else{
view = LayoutInflater.from(context).inflate(R.layout.layout_item2,null);
holder = new ViewHolder2(view);
}
return holder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
if (getItemViewType(position) == 0){
((ViewHolder1) holder).name.setText(list.get(position).getName());
((ViewHolder1) holder).summary.setText(list.get(position).getSummary());
Glide.with(context).load(list.get(position).getImageUrl()).diskCacheStrategy(DiskCacheStrategy.ALL).into(((ViewHolder1) holder).image);
}else if (getItemViewType(position) == 2){
((ViewHolder2) holder).name2.setText(list.get(position).getName());
((ViewHolder2) holder).summary2.setText(list.get(position).getSummary());
Glide.with(context).load(list.get(position).getImageUrl()).diskCacheStrategy(DiskCacheStrategy.ALL).into(((ViewHolder2) holder).image2);
}else if (getItemViewType(position) == 1){
//设置圆角角度
RoundedCorners corners = new RoundedCorners(100);
RequestOptions override = RequestOptions.bitmapTransform(corners).override(100,160);
((ViewHolder3) holder).name3.setText(list.get(position).getName());
Glide.with(context).load(list.get(position).getImageUrl()).apply(override).diskCacheStrategy(DiskCacheStrategy.ALL).into(((ViewHolder3) holder).image3);
}
if (itemClickListener != null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
itemClickListener.onItemClick(position);
}
});
}
}
@Override
public int getItemCount() {
if (list != null){
return list.size();
}
return 0;
}
public class ViewHolder1 extends RecyclerView.ViewHolder {
TextView name, summary;
ImageView image;
public ViewHolder1(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name_id);
summary = itemView.findViewById(R.id.summary_id);
image = itemView.findViewById(R.id.image_id);
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder{
TextView name2,summary2;
ImageView image2;
public ViewHolder2(View itemView) {
super(itemView);
name2 = itemView.findViewById(R.id.name_id2);
summary2 = itemView.findViewById(R.id.summary_id2);
image2 = itemView.findViewById(R.id.image_id2);
}
}
public class ViewHolder3 extends RecyclerView.ViewHolder{
ImageView image3;
TextView name3;
public ViewHolder3(View itemView) {
super(itemView);
image3 = itemView.findViewById(R.id.image_id3);
name3 = itemView.findViewById(R.id.name_id3);
}
}
}