电商XRecyclerView展示,搜索,布局切换

电商XRecyclerView展示,搜索,布局切换电商XRecyclerView展示,搜索,布局切换
加入权限

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

加入依赖

 implementation('com.jcodecraeer:xrecyclerview:1.5.9') { exclude group: 'com.android.support' }
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.github.bumptech.glide:glide:3.8.0'
implementation 'com.android.support:recyclerview-v7:27.1.1'

导入gson.jar包
写Bean类
Goods
http://www.zhaoapi.cn/product/searchProducts?keywords=手机

 private double bargainPrice;
private String createtime;
private String detailUrl;
private String images;
private int num;
private int pid;
private double price;
private int pscid;
private int selected;
private int sellerid;
private String subhead;
private String title;

写Result

public class Result<T> {
int code;
String msg;
T data;

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

public T getData() {
    return data;
}

public void setData(T data) {
    this.data = data;
}
}

在Utils包中写
HttpUtils

public class HttpUtils {
public static String get(String urlString){

    OkHttpClient okHttpClient = new OkHttpClient();

    Request request = new Request.Builder().url(urlString).get().build();

    try {
        Response response = okHttpClient.newCall(request).execute();

        return response.body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

public static String postForm(String url,String[] name,String[] value){

    OkHttpClient okHttpClient = new OkHttpClient();

    FormBody.Builder formBuild = new FormBody.Builder();
    for (int i = 0; i < name.length; i++) {
        formBuild.add(name[i],value[i]);
    }

    Request request = new Request.Builder().url(url).post(formBuild.build()).build();

    try {
        Response response = okHttpClient.newCall(request).execute();

        String result = response.body().string();
        Log.i("dt",result);
        return result;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

public static String postFile(String url,String[] name,String[] value,String fileParamName,File file){

    OkHttpClient okHttpClient = new OkHttpClient();

    MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
    if(file != null){
        // MediaType.parse() 里面是上传的文件类型。
        RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
        String filename = file.getName();
        // 参数分别为: 文件参数名 ,文件名称 , RequestBody
        requestBody.addFormDataPart(fileParamName, "jpg", body);
    }
    if (name!=null) {
        for (int i = 0; i < name.length; i++) {
            requestBody.addFormDataPart(name[i], value[i]);
        }
    }

    Request request = new Request.Builder().url(url).post(requestBody.build()).build();

    try {
        Response response = okHttpClient.newCall(request).execute();
        if (response.code()==200) {
            return response.body().string();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

public static String postJson(String url,String jsonString){

    OkHttpClient okHttpClient = new OkHttpClient();

    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonString);

    Request request = new Request.Builder().url(url).post(requestBody).build();

    try {
        Response response = okHttpClient.newCall(request).execute();

        return response.body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
}

在core包里写
BasePresenter

public abstract class BasePresenter {

DataCall dataCall;

public BasePresenter(DataCall dataCall){
    this.dataCall = dataCall;
}


Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {

        Result result = (Result) msg.obj;
        if (result.getCode()==0){
            dataCall.success(result.getData());
        }else{
            dataCall.fail(result);
        }
    }
};



public void requestData(final Object...args){
    new Thread(new Runnable() {
        @Override
        public void run() {


            Message message = mHandler.obtainMessage();
            message.obj = getData(args);
            mHandler.sendMessage(message);

        }
    }).start();
}

protected abstract Result getData(Object...args);

public void unBindCall(){
    this.dataCall = null;
}

}

写下接口DataCall

public interface DataCall<T> {

void success(T data);

void fail(Result result);

}

写下DTApplication

public class DTApplication extends Application {

private static DTApplication instance;
private SharedPreferences mSharedPreferences;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;
    mSharedPreferences = getSharedPreferences("application",
            Context.MODE_PRIVATE);
}

public static DTApplication getInstance() {
    return instance;
}

public SharedPreferences getShare() {
    return mSharedPreferences;
}

}

在M层写model包写
GoodsListModel

public class GoodsListModel {

public static Result goodsList(String keywords, final String page,final String sort) {
    String resultString = HttpUtils.postForm("http://www.zhaoapi.cn/product/searchProducts",
            new String[]{"keywords", "page","sort"}, new String[]{keywords, page,sort});

    try {
        Gson gson = new Gson();

        Type type = new TypeToken<Result<List<Goods>>>() {
        }.getType();

        Result result = gson.fromJson(resultString, type);
      return result;
    } catch (Exception e) {

    }
    Result result = new Result();
    result.setCode(-1);
    result.setMsg("数据解析异常");
    return result;
}
}

P层在presenter包里写
GoodsListPresenter

public class GoodsListPresenter extends BasePresenter {

private int page=1;
private boolean isRefresh=true;
private String sort=0+"";


public GoodsListPresenter(DataCall dataCall) {
    super(dataCall);
}

@Override
protected Result getData(Object... args) {
    isRefresh = (boolean) args[0];
    if (isRefresh){
        page = 1;
    }else{
        page++;
    }
    Result result = GoodsListModel.goodsList((String)args[1],page+"",sort);
    return result;
}

public boolean isResresh(){
    return isRefresh;
}
}

把图库,颜色库导入
写主界面布局

<?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"
android:orientation="vertical"
tools:context=".activity.MainActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <ImageView
        android:id="@+id/btn_back"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:padding="15dp"
        android:src="@drawable/btn_back" />

    <ImageView
        android:id="@+id/btn_layout"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:padding="15dp"
        android:src="@drawable/even_city_draw" />

    <EditText
        android:id="@+id/edit_keywords"
        android:layout_width="match_parent"
        android:layout_height="36dp"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/btn_layout"
        android:layout_toRightOf="@+id/btn_back"
        android:background="@drawable/search_edit_bg"
        android:hint="搜索"
        android:text="手机"
        android:paddingLeft="40dp"
        android:singleLine="true"
        android:textColorHint="@color/grayblack"
        android:textColor="@color/custom_gray"
        android:layout_marginRight="5dp"
        android:textSize="16sp" />

    <ImageView
        android:id="@+id/btn_search"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignLeft="@+id/edit_keywords"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:src="@android:drawable/ic_search_category_default" />
    <ImageView
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignRight="@+id/edit_keywords"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/person_list_sound_up" />
</RelativeLayout>

<ImageView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:src="@android:color/darker_gray" />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/cate_text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textColor="@color/set_font_color"
        android:gravity="center"
        android:textSize="14sp"
        android:text="综合▲">
    </TextView>
    <TextView
        android:id="@+id/cate_text2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textColor="@color/set_font_color"
        android:gravity="center"
        android:textSize="14sp"
        android:text="价格▲">
    </TextView>
    <TextView
        android:id="@+id/cate_text3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textColor="@color/set_font_color"
        android:gravity="center"
        android:textSize="14sp"
        android:text="销量▲">
    </TextView>
    <TextView
        android:id="@+id/cate_text4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:textColor="@color/set_font_color"
        android:gravity="center"
        android:textSize="14sp"
        android:text="筛选▲">
    </TextView>
</LinearLayout>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:src="@android:color/darker_gray" />

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

</com.jcodecraeer.xrecyclerview.XRecyclerView>
</LinearLayout>

@drawable/search_edit_bg

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<corners android:radius="20dp" />
<solid
    android:color="#d8d8d8"></solid>

</shape>

列表布局

<?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:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:minHeight="50dp"
    android:src="@mipmap/ic_launcher"/>

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="aa"
    android:padding="10dp"/>

</LinearLayout>

线性布局

<?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:id="@+id/image"
    android:layout_margin="10dp"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:minHeight="50dp"
    android:src="@mipmap/ic_launcher"/>

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="aa"
    android:padding="10dp"/>

</LinearLayout>

在adapter包写适配器
GoodsListAdapter

public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.GoodsHodler> {

private List<Goods> mList = new ArrayList<>();
private Context context;


public final static int LINEAR_TYPE = 0;
public final static int GRID_TYPE = 1;

private int viewType = LINEAR_TYPE;

private OnItemClickListener onItemClickListener;

public GoodsListAdapter(Context context) {
    this.context = context;
}

@Override
public int getItemViewType(int position) {
    return viewType;
}


public void setViewType(int viewType) {
    this.viewType = viewType;
}


@NonNull
@Override
public GoodsHodler onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
    View view = null;
    if (viewType == LINEAR_TYPE) {
        view = View.inflate(viewGroup.getContext(), R.layout.goods_linear_item, null);
    } else {
        view = View.inflate(viewGroup.getContext(), R.layout.goods_grid_item, null);
    }
    GoodsHodler goodsHodler = new GoodsHodler(view);

    return goodsHodler;
}

@Override
public void onBindViewHolder(@NonNull GoodsHodler goodsHodler, int position) {
    final Goods goods = mList.get(position);

    goodsHodler.itemView.setTag(mList.get(position));


    goodsHodler.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context,WebActivity.class);
            intent.putExtra("url",goods.getDetailUrl());
            context.startActivity(intent);

        }
    });

    goodsHodler.text.setText(goods.getTitle());
   
    String imageurl = "https" + goods.getImages().split("https")[1];
    Log.i("dt", "imageUrl: " + imageurl);
    imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length());
    Glide.with(context).load(imageurl).into(goodsHodler.imageView);
}

public static void main(String[] args) {
    String aa = "a111a222a333a";
    String[] b = aa.split("a");
    System.out.println(b[0]);
}

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

public void addAll(List<Goods> data) {
    if (data != null) {
        mList.addAll(data);
    }
}


public void clearList() {
    mList.clear();
}


public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

class GoodsHodler extends RecyclerView.ViewHolder {
    TextView text;
    ImageView imageView;

    public GoodsHodler(@NonNull View itemView) {
        super(itemView);
        text = itemView.findViewById(R.id.text);
        imageView = itemView.findViewById(R.id.image);
    }
}


public interface OnItemClickListener {
    void onItemClick(Goods goods);
}

}
主界面MainActivity
MainActivity

public class MainActivity extends AppCompatActivity implements XRecyclerView.LoadingListener,
    DataCall<List<Goods>>, View.OnClickListener,GoodsListAdapter.OnItemClickListener {

private XRecyclerView mRecyclerView;
private GoodsListAdapter mAdapter;
private LinearLayoutManager mLinearManager;
private GridLayoutManager mGridManager;

private static final int GRID_LAYOUT_MANAGER = 1;
private static final int LINEAR_LAYOUT_MANAGER = 2;


private ImageView mBtnLayout;
private EditText mKeywordsEdit;
private int sort;

private GoodsListPresenter mPresenter;
private TextView t1;
private TextView t2;
private TextView t3;
private TextView t4;
private String keywords;
private List<Goods> lists  = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    t1 = findViewById(R.id.cate_text1);
    t2 = findViewById(R.id.cate_text2);
    t3 = findViewById(R.id.cate_text3);
    t4 = findViewById(R.id.cate_text4);
    t1.setOnClickListener(this);
    t2.setOnClickListener(this);
    t3.setOnClickListener(this);
    t4.setOnClickListener(this);
    mKeywordsEdit = findViewById(R.id.edit_keywords);
    mBtnLayout = findViewById(R.id.btn_layout);

    findViewById(R.id.btn_search).setOnClickListener(this);
    mBtnLayout.setOnClickListener(this);

    mRecyclerView = findViewById(R.id.list_goods);
    mRecyclerView.setLoadingListener(this);
    mPresenter = new GoodsListPresenter(this);
    keywords = mKeywordsEdit.getText().toString();
    mPresenter.requestData(true, keywords,sort+"");

    mGridManager = new GridLayoutManager(this, 2,
            GridLayoutManager.VERTICAL, false);//网格布局
    mLinearManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);//线性布局
    mRecyclerView.setLayoutManager(mLinearManager);

    mAdapter = new GoodsListAdapter(this);
    mAdapter.setOnItemClickListener(this);
    mRecyclerView.setAdapter(mAdapter);

    //加载数据
   mRecyclerView.refresh();//刷新
}

@Override
public void onRefresh() {
    keywords = mKeywordsEdit.getText().toString();
    mPresenter.requestData(true, keywords,sort+"");
}

@Override
public void onLoadMore() {
    keywords = mKeywordsEdit.getText().toString();

    mPresenter.requestData(false, keywords,sort+"");
}

@Override
public void success(List<Goods> data) {
    mRecyclerView.refreshComplete();//结束刷新
    mRecyclerView.loadMoreComplete();//结束加载更多
    if (mPresenter.isResresh()) {
        mAdapter.clearList();
    }
    mAdapter.addAll(data);
    mAdapter.notifyDataSetChanged();
}

@Override
public void fail(Result result) {
    mRecyclerView.refreshComplete();
    mRecyclerView.loadMoreComplete();
    Toast.makeText(this, result.getCode() + "  " + result.getMsg(),
            Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    mPresenter.unBindCall();
}

private boolean isGrid = false;

@Override
public void onClick(View v) {
    if (v.getId() == R.id.btn_search) {//搜索
        String keywords = mKeywordsEdit.getText().toString();
        mPresenter.requestData(true, keywords,sort+"");
    } else if (v.getId() == R.id.btn_layout) {//切换布局


        if (mRecyclerView.getLayoutManager().equals(mLinearManager)) {

            isGrid = true;
            mAdapter.setViewType(GoodsListAdapter.GRID_TYPE);
            mRecyclerView.setLayoutManager(mGridManager);
        } else {
            isGrid = false;
            mAdapter.setViewType(GoodsListAdapter.LINEAR_TYPE);
            mRecyclerView.setLayoutManager(mLinearManager);
        }
        mAdapter.notifyDataSetChanged();
    }else{
        switch (v.getId()){
            case R.id.cate_text1:
                sort = 0;
                keywords = mKeywordsEdit.getText().toString();
                Toast.makeText(MainActivity.this,"综合排序",Toast.LENGTH_SHORT).show();
                mPresenter.requestData(true, keywords,sort+"");
                break;
            case R.id.cate_text2:
                sort = 1;
                keywords = mKeywordsEdit.getText().toString();
                Toast.makeText(MainActivity.this,"价格排序",Toast.LENGTH_SHORT).show();
                mPresenter.requestData(true, keywords,sort+"");
                break;
            case R.id.cate_text3:
                sort = 2;
                keywords = mKeywordsEdit.getText().toString();
                Toast.makeText(MainActivity.this,"销量排序",Toast.LENGTH_SHORT).show();
                mPresenter.requestData(true, keywords,sort+"");
                break;

        }
        mAdapter.notifyDataSetChanged();
    }


}

@Override
public void onItemClick(Goods goods) {
    Intent intent = new Intent(this,WebActivity.class);
    intent.putExtra("url",goods.getDetailUrl());
    startActivity(intent);
}
}

WebView布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

WebActivity

public class WebActivity extends AppCompatActivity {
WebView mWebView;

@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);

    mWebView = (WebView) findViewById(R.id.webview);

    WebSettings webSettings = mWebView.getSettings();

 
    webSettings.setJavaScriptEnabled(true);

    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

    String url = getIntent().getStringExtra("url");
    Log.i("dt", url);


    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
         
         
            return false;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
          
            return false;
        }
    });

 
    mWebView.setWebChromeClient(new WebChromeClient());

}

}