<?  version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout  ns:android=\"http://schemas.android.com/apk/res/android\"
     ns:app=\"http://schemas.android.com/apk/res-auto\"
     ns: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>

mainactivity

public class MainActivity extends AppCompatActivity implements XRecyclerView.LoadingListener,
        DataCall<List<Goods>>, View. Listener,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;

    //新建商品列表Presenter
    private GoodsListPresenter mPresenter = new GoodsListPresenter(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mKeywordsEdit = findViewById(R.id.edit_keywords);
        mBtnLayout = findViewById(R.id.btn_layout);

        findViewById(R.id.btn_search).set Listener(this);
        mBtnLayout.set Listener(this);

        mRecyclerView = findViewById(R.id.list_goods);//查找mRecyclerView
        mRecyclerView.setLoadingListener(this);//添加下拉和刷新的监听器

//        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        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() {
        String keywords = mKeywordsEdit.getText().toString();
        mPresenter.requestData(true, keywords);
    }

    @Override
    public void  More() {
        String keywords = mKeywordsEdit.getText().toString();
        mPresenter.requestData(false, keywords);
    }
    private boolean isGrid=false;
    @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();
    }

    @Override
    public void  (View v) {
        if (v.getId() == R.id.btn_search) {//搜索
            String keywords = mKeywordsEdit.getText().toString();
            mPresenter.requestData(true, keywords);
        } else if (v.getId() == R.id.btn_layout) {//切换布局
//            if (!isGrid) {
            if (mRecyclerView.getLayoutManager().equals(mLinearManager)) {
//            if (mAdapterm.getItemViewType(0) == GoodsListAdapter.LINEAR_TYPE) {
                isGrid = true;
                mAdapter.setViewType(GoodsListAdapter.GRID_TYPE);
                mRecyclerView.setLayoutManager(mGridManager);
            } else {
                isGrid = false;
                mAdapter.setViewType(GoodsListAdapter.LINEAR_TYPE);
                mRecyclerView.setLayoutManager(mLinearManager);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

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

goodsadapter`package com.dingtao.week3.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dingtao.week3.R;
import com.dingtao.week3.activity.MainActivity;
import com.dingtao.week3.activity.WebActivity;
import com.dingtao.week3.bean.Goods;

import java.util.ArrayList;
import java.util.List;

/**

  • @author dingtao

  • @date 2018/12/13 19:11

  • qq:1940870847
    */
    public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.GoodsHodler> {

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

    public final static int LINEAR_TYPE = 0;//线性
    public final static int GRID_TYPE = 0;//网格

    private int viewType = LINEAR_TYPE;

    private OnItemClickListener onItemClickListener;

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

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

    //设置item的视图类型
    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) {//通过第二个参数viewType判断选用的视图
    view = View.inflate(viewGroup.getContext(), R.layout.goods_linear_item, null);//加载item布局
    } else {
    view = View.inflate(viewGroup.getContext(), R.layout.goods_grid_item, null);//加载item布局
    }
    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.set Listener(new View. Listener() {
         @Override
         public void  (View v) {
             Intent intent = new Intent(context,WebActivity.class);
             intent.putExtra(\"url\",goods.getDetailUrl());
             context.startActivity(intent);
    

// onItemClickListener.onItemClick(goods);
}
});

    goodsHodler.text.setText(goods.get ());
    //由于我们的数据图片提供的不标准,所以我们需要切割得到图片
    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(MainActivity 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);
    }
}

/**
 * @author dingtao
 * @date 2018/12/15 10:28 AM
 * 点击接口
 */
public interface OnItemClickListener {
    void onItemClick(Goods goods);
}

}
precenter

public abstract class  Presenter {
    DataCall dataCall;

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


    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Result result = (Result) msg.obj;
            if (result.getCode()==0){
                dataCall.success(result.getData());
            }else{
                dataCall.fail(result);
            }
        }
    };



    public void requestData(final  ...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( ...args);
    public void unBindCall(){
        this.dataCall = null;
    }
}

goodsprecenter

public class GoodsListPresenter extends  Presenter {

    private int page=1;
    private boolean isRefresh=true;

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

    @Override
    protected Result getData( ... args) {
        isRefresh = (boolean) args[0];//是否需要刷新
        if (isRefresh){//刷新
            page = 1;
        }else{
            page++;
        }
        Result result = GoodsListModel.goodsList((String)args[1],page+\"\");//调用网络请求获取数据
        return result;
    }

    public boolean isResresh(){
        return isRefresh;
    }
}

model

public class GoodsListModel {

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

        try {
            Gson gson = new Gson();

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

            Result result = gson.fromJson(resultString, type);
//        Result<List<Goods>> result = new Result<>();
//        result.setCode(0);
//        List<Goods> list = new ArrayList<>();
//        for (int i = 0; i < 30; i++) {
//            Goods goods = new Goods();
//            goods.setImages(\"\");
//            goods.set (\"手机\"+i);
//            list.add(goods);
//        }
//        result.setData(list);

            return result;
        } catch (Exception e) {

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

}

http

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 \"\";
}

}


收藏 打印