XRecyclerView + Okhttp_get + Glide

XRecyclerView + Okhttp_get + Glide

还是有点小瑕疵的:

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

 

例:

XRecyclerView + Okhttp_get + Glide_第1张图片

 

 

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

依赖:

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:+'

}

 

权限:

  

 

主线程:

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 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 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();
                        }

                    }
                });
            }
        });

    }
    
}

主线程布局:




    
    

    
        
        
    

 

适配器:

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 {
    private List list = new ArrayList<>();
    private Context context;// 传参添加

    public MyAdapter(List 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);
        }
    }
}

适配器 的布局:




    
    
    

 

 

跳转的详情页:

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);

    }

}

详情页 的布局:



    
    
        
        
        
    


    
        
        
        
        
        
        
        

        
    

 

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

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

你可能感兴趣的:(项目开发,RecyclerView,列表展示,上下拉刷新)