XRecyclerView + Okhttp_get + Glide

XRecyclerView + Okhttp_get + Glide

还是有点小瑕疵的:

  1. 未采用异步加载(这个可以换成自己的网络加载框架)
  2. 上拉加载没有动画效果(这个自己在网上巴拉一个就行)
  3. 在布局里报错的话换成自己的图片就行了
  4. 图片加载我采用的是Glide,fresco有一个致命的缺陷,无法自适应图片的宽高

 

例:

 

 

废话不多说,直接上代码:

依赖:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    //okhttp
    implementation 'net.qiujuer.common:okhttp:3.0.0'
    implementation 'com.google.code.gson:gson:2.2.4'

    //xrecyclerview上拉刷新,下拉加载
    implementation 'com.jcodecraeer:xrecyclerview:1.3.2'

    //圆形图片依赖:(一般和glide一起用):
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    //图片依赖比imagerloader更方便:
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.facebook.fresco:fresco:+'

}

 

权限:

  <uses-permission android:name="android.permission.INTERNET"/>

 

主线程:

package com.sgy.sgy_xrec;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 沈晖然
 * XRecyclerView + Okhttp_get + Glide
 * XRecyclerView 下拉刷新,上拉加载
 * http://live.9158.com/Room/GetHotLive_v2?page=1&lon=0.0&province=&lat=0.0&type=1
 * http://live.9158.com/Room/GetHotLive_v2?
 * 分页加载 page=1
 * &lon=0.0&province=&lat=0.0&type=1
 */
public class MainActivity extends AppCompatActivity {
    //SP存储
    public SharedPreferences login;
    public String token;
    
    public String xrcurl = Api.HTTP_URL + "lon=0.0&province=&lat=0.0&type=1";
    public int page = 1;// 分页加载 (有的默认是1,有的是零,具体看后台咋设置)
    private List<MyBean.DataBean.ListBean> xrclist = new ArrayList<>();
    private XRecyclerView xrc;
    private MyAdapter myadapter;//XRecyclerView 适配器
    private RelativeLayout jindutiao; //代码中控制显隐藏
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        xrecyc_view();//XRecyclerView 各种配置

    }

    /**
     * XRecyclerView 各种配置
     */
    public void xrecyc_view() {
        //代码中控制显隐藏
        jindutiao = (RelativeLayout) findViewById(R.id.jindutiao);
        xrc= (XRecyclerView) findViewById(R.id.xrc_xrecycview);//找控件 XRecyclerView

        //设置可上拉,下拉
        xrc.setPullRefreshEnabled(true);
        xrc.setLoadingMoreEnabled(true);

        // 设置加载样式 
        xrc.setRefreshProgressStyle(ProgressStyle.BallPulseRise);
        xrc.setLoadingMoreProgressStyle(ProgressStyle.BallPulseRise);

        // 线性布局管理器   VERTICAL默认样式/竖向显示       第三个参数是数据是否到过来显示
        LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false);
//        LinearLayoutManager manager = new GridLayoutManager(this,2);//表格布局,后面的2代表(2列)
        xrc.setLayoutManager(manager);//添加布局管理器

        //设置上拉,下拉的监听事件
        xrc.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                xrclist.clear();//清除集合
                page = 1;//刷新页面
                getHttp();
                myadapter.notifyDataSetChanged();//刷新界面
                xrc.refreshComplete();//刷新数据完成(取消刷新动画)
                jindutiao.setVisibility(View.INVISIBLE);//隐藏
            }

            @Override
            public void onLoadMore() {
                page ++;//加载更多
                getHttp();
                myadapter.notifyDataSetChanged();//刷新界面
                xrc.loadMoreComplete(); //加载数据完成(取消加载动画)
                jindutiao.setVisibility(View.INVISIBLE);//隐藏
            }
        });
        getHttp();//okhttp get请求
    }
    
    /**
     * okhttp get请求
     */
    public void getHttp() {
        // sp 获取token
//        login = getSharedPreferences( "login", 0 );
//        token = login.getString( "token", "" );
//        Log.d("111111 - token>>:", token);

        jindutiao.setVisibility(View.VISIBLE);//显示
        jindutiao.setClickable(true);//禁止点击

        Log.d("111111 - xrcurl>>:",xrcurl);
        Request.Builder builder = new Request.Builder()
                .url(  xrcurl + "&page="+ page  )
                .addHeader( "token", "" );//由于是自己写的Demo,就不需要token,所以就置空

        Request build = builder.build();

        OkHttpClient client = new OkHttpClient.Builder().readTimeout( 5000, TimeUnit.SECONDS ).build();
        Call call = client.newCall( build );
        call.enqueue( new Callback() {
            @Override
            public void onFailure(Call call, IOException e) { }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功返回结果,如果希望返回的是字符串
                final String responseData=response.body().string();
                // 如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
                // InputStream responseStream=response.body().byteStream();
                // 注意,此时的线程不是ui线程,如果此时我们要用返回的数据进行ui更新,操作控件,就要使用相关方法
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        MyBean data = new Gson().fromJson(responseData , MyBean.class);
                        // 判断是否请求到数据
                        if(data.getData()!=null){
                            //创建一个 局部的List集合,把获取的数据存进去
                            List<MyBean.DataBean.ListBean> list2 = new ArrayList<>();
                            list2.addAll(data.getData().getList());
                            //在把这个 局部的List集合>>传到外面的 全局list里,每次上拉加载更多都会传进去,以此来实现加载更多的功能
                            xrclist.addAll(list2);
                            if (myadapter==null){
                                //判断是否为空,把全局list传入适配器,并且加载XRecyclerView
                                myadapter = new MyAdapter(xrclist, MainActivity.this);
                                xrc.setAdapter(myadapter);

                                jindutiao.setVisibility(View.INVISIBLE);//隐藏
                            }else {
                                myadapter.notifyDataSetChanged();
                            }
                        }else {
                            //重新登录
//                            login = getSharedPreferences( "login", 0 );
//                            SharedPreferences.Editor edit = login.edit();
//                            edit.clear(); //通过清除SharedPreferences里的数据来达到退出登录的目的
//                            edit.commit();//提交数据

//                            Intent intent = new Intent( MainActivity.this, LoginActivity.class );
//                            startActivity( intent );
//                            Toast.makeText( getActivity(), "请求失败,请重新登录", Toast.LENGTH_SHORT ).show();
                        }

                    }
                });
            }
        });

    }
    
}

主线程布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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=".MainActivity">

    <com.jcodecraeer.xrecyclerview.XRecyclerView
        android:id="@+id/xrc_xrecycview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </com.jcodecraeer.xrecyclerview.XRecyclerView>

    <RelativeLayout
        android:id="@+id/jindutiao"
        android:background="#4Dffffff"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="invisible">
        <ProgressBar
            android:layout_centerInParent="true"
            android:layout_gravity="center_horizontal"
            android:layout_width="80dp"
            android:layout_height="80dp"/>
        <TextView
            android:paddingTop="130dp"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="数据过多,请耐心等待.."
            android:textColor="#333333"/>
    </RelativeLayout>

</RelativeLayout>

 

适配器:

package com.sgy.sgy_xrec;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;

/**
 * 沈晖然
 * XRecyclerView 适配器 Adapter
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private List<MyBean.DataBean.ListBean> list = new ArrayList<>();
    private Context context;// 传参添加

    public MyAdapter(List<MyBean.DataBean.ListBean> list , Context context) {
        this.context = context;// 传参添加
        this.list = list;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.my_itme,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        // Glide 请求图片
        Glide.with(context).load(list.get(position).getSmallpic()).into(holder.my_1);
        holder.my_2.setText(list.get(position).getMyname());
        holder.my_3.setText(list.get(position).getGps());

        //点击条目 holder.itemView.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent( context, MainTextActivity.class );
                intent.putExtra("myname1", list.get(position).getSmallpic());//图片
                intent.putExtra("myname2", list.get(position).getMyname());//昵称
                intent.putExtra("myname3", list.get(position).getGps());//地址
                context.startActivity( intent );
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView my_1;
        private TextView my_2;
        private TextView my_3;
        public MyViewHolder(View itemView) {
            super(itemView);
            my_1=itemView.findViewById(R.id.my_itme_01);
            my_2=itemView.findViewById(R.id.my_itme_02);
            my_3=itemView.findViewById(R.id.my_itme_03);
        }
    }
}

适配器 的布局:

<?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="wrap_content">

    <ImageView
        android:id="@+id/my_itme_01"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:src="@drawable/mmm"/>
    <TextView
        android:id="@+id/my_itme_02"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="15dp"
        android:text="myname昵称"
        android:textColor="#333333"
        android:textSize="18dp"
        android:textStyle="bold"/>
    <TextView
        android:id="@+id/my_itme_03"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="50dp"
        android:text="gps地址"
        android:textColor="#333333"
        android:textSize="18dp" />
</RelativeLayout>

 

 

跳转的详情页:

package com.sgy.sgy_xrec;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;

/**
 * 沈晖然
 * 列表详情展示
 */
public class MainTextActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintext);
        TextView text_2 = findViewById(R.id.text_2);//待定
        ImageView fanhui = findViewById(R.id.text_1);
        fanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();//关闭当前页面,以此来达到返回上一页面的效果
            }
        });

        ImageView text_01 = findViewById(R.id.text_01);
        TextView text_02 = findViewById(R.id.text_02);
        TextView text_03 = findViewById(R.id.text_03);
        WebView text_04 = findViewById(R.id.text_04);

        Intent intent = getIntent();
        String name1 = intent.getStringExtra("myname1");//图片
        String name2 = intent.getStringExtra("myname2");//昵称
        String name3 = intent.getStringExtra("myname3");//地址
        String name4 = intent.getStringExtra("myname4");// WebView 富文本

        // Glide 请求图片
        Glide.with(this).load(name1).into(text_01);
        text_02.setText(name2);
        text_03.setText(name3);

//        // 加载 WebView 富文本
//        text_04.loadDataWithBaseURL(null, Html.fromHtml(name4)+"", "text/html",  "utf-8", null);

//        //时间截取
//        String str1 = name1 ;
//        str1 = str1.substring(0,16);//开始时间
//        text_01.setText(str1);

    }

}

详情页 的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!--头部布局 #DF3031-->
    <RelativeLayout
        android:background="#DF3031"
        android:layout_width="match_parent"
        android:layout_height="48dp">
        <ImageView
            android:id="@+id/text_1"
            android:padding="14dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/back_sele"/>
        <TextView
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="详情"
            android:textSize="16dp"
            android:textColor="#ffffff"/>
        <TextView
            android:id="@+id/text_2"
            android:padding="14dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="待定"
            android:textSize="16dp"
            android:textColor="#ffffff"/>
    </RelativeLayout>


    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/text_01"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/mmm"/>
        <!--控件居中-->
        <!--android:layout_gravity="center_horizontal"-->
        <!--控件里的 内容居中-->
        <!--android:gravity="center_horizontal"-->
        <TextView
            android:id="@+id/text_02"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center_horizontal"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="15dp"
            android:text="myname昵称"
            android:textColor="#333333"
            android:textSize="18dp"
            android:textStyle="bold"/>
        <TextView
            android:id="@+id/text_03"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center_horizontal"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"
            android:layout_marginTop="15dp"
            android:text="gps地址"
            android:textColor="#333333"
            android:textSize="18dp" />

        <WebView
            android:id="@+id/text_04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="15dp"
            android:text="WebView..."
            android:textSize="14dp"
            android:textColor="#333333"
            android:lines="6"
            android:ellipsize="end"
            android:lineSpacingExtra="5dp"/>
    </LinearLayout>
</LinearLayout>

 

网络环境(把链接换成自己的就行了,这个网络会失效):

package com.sgy.sgy_xrec;

/**
 * shr
 * 沈晖然
 */
public class Api {
    //正式环境
    //http://live.9158.com/Room/GetHotLive_v2?page=1&lon=0.0&province=&lat=0.0&type=1
    public static final String HTTP_URL="http://live.9158.com/Room/GetHotLive_v2?";
}

 

 

有问题欢迎私聊,毕竟技术的进步在于交流:

微信:18310812141

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值