<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
实现布局效果:
activity_main
<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="view.MainActivity">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:textSize="25dp"
android:text="搜索商品"/>
<ImageView
android:layout_height="30dp"
android:layout_width="30dp"
android:src="@drawable/lv_icon"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:id="@+id/imageView"/>
<View
android:layout_height="2dp"
android:layout_width="match_parent"
android:layout_marginTop="15dp"
android:id="@+id/view"
android:layout_below="@id/imageView"
android:background="#da5a5c5a"/>
<EditText
android:layout_height="wrap_content"
android:layout_width="200dp"
android:layout_marginTop="21dp"
android:id="@+id/editText"
android:layout_below="@+id/view"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:hint="请输入关键字"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="搜索" android:id="@+id/button"
android:layout_toRightOf="@+id/editText"
android:layout_toEndOf="@+id/editText"
android:layout_marginStart="21dp"
android:layout_marginLeft="21dp"
android:layout_alignBottom="@+id/editText"/>
<View
android:layout_height="2dp"
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:id="@+id/v"
android:layout_below="@id/button"
android:background="#da5a5c5a"/>
<com.jcodecraeer.xrecyclerview.XRecyclerView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/xrecyclerview"
android:layout_below="@id/v"/>
</RelativeLayout>
item布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/image"
android:layout_toEndOf="@+id/image" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_below="@id/textView"
android:layout_toRightOf="@id/image"
android:layout_marginTop="20dp"
android:textColor="#f2052d"/>
</RelativeLayout>
item2布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_below="@+id/image"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginTop="15dp"
android:textColor="#f2052d"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
代码:
Bean
DataBeans:
public class ListBean {
private String img;
private String title;
private String price;
public ListBean(String img, String title, String price) {
this.img = img;
this.title = title;
this.price = price;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
M层
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private Context context;
private List<ListBean> list;
private int j;
public Adapter(Context context, List<ListBean> list,int j) {
this.context = context;
this.list = list;
this.j=j;
}
//创建ViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//子条目布局
if(j==1){
View view = View.inflate(context, R.layout.item, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}else{
View view = View.inflate(context, R.layout.item2, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
}
//绑定ViewHolder,把数据和视图进行绑定
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
Glide.with(context).load(list.get(position).getImg()).into(holder.image);
holder.textview.setText(list.get(position).getTitle());
holder.textview2.setText(list.get(position).getPrice());
}
@Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView textview;
private TextView textview2;
private ImageView image;
public ViewHolder(View itemView) {
super(itemView);
//itemView一个条目的视图
image = (ImageView)itemView.findViewById(R.id.image);
textview = (TextView)itemView.findViewById(R.id.textView);
textview2 = (TextView)itemView.findViewById(R.id.textView2);
}
}
}
Logger:
public class Logger implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl url=original.url().newBuilder()
.addQueryParameter("source","android")
.build();
//添加请求头
Request request = original.newBuilder()
.url(url)
.build();
return chain.proceed(request);
}
}
P层
public class Presenter {
private Context context;
private Iv iv;
public Presenter(Context context, Iv iv) {
this.context = context;
this.iv = iv;
}
public void get(String str,int i){
Map map = new HashMap<String,String>();
map.put("keywords",str+"");
map.put("page",i+"");
OkHttpUtils.getInstance().get("http://120.27.23.105/product/searchProducts", map, new CallBack() {
@Override
public void onSuccess(Object o) {
DataBeans databeans = (DataBeans)o;
List<DataBeans.DataBean> data = databeans.getData();
List list = new ArrayList<ListBean>();
for(int i=0;i<data.size();i++){
String images = data.get(i).getImages();
String[] split = images.split("!");
Log.i("TAG",split[0]);
list.add(new ListBean(split[0],data.get(i).getTitle(),data.get(i).getPrice()+""));
}
iv.onSuccess(list);
}
@Override
public void onFailed(Exception e) {
}
},DataBeans.class);
}
public void onremove(){
if (iv!=null){
iv=null;
}
}
}
Ok封装
public class OkHttpUtils {
private static volatile OkHttpUtils instance;
private static Handler handler = new Handler();
private OkHttpUtils(){
}
public static OkHttpUtils getInstance() {
if (instance == null) {
synchronized (OkHttpUtils.class) {
if (instance == null) {
instance = new OkHttpUtils();
}
}
}
return instance;
}
public void get(String url, Map<String,String> map, final CallBack callBack, final Class c) {
//对url和参数做拼接处理
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(url);
//判断是否存在? if中是存在
if (stringBuffer.indexOf("?") != -1) {
//判断?是否在最后一位 if中是不在最后一位
if (stringBuffer.indexOf("?") != stringBuffer.length() - 1) {
stringBuffer.append("&");
}
} else {
stringBuffer.append("?");
}
for (Map.Entry<String, String> entry : map.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append("&");
}
//判断是否存在& if中是存在
if (stringBuffer.indexOf("&") != -1) {
stringBuffer.deleteCharAt(stringBuffer.lastIndexOf("&"));
}
Log.i("TAG",stringBuffer.toString());
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.addInterceptor(new Logger())
.build();
Request request = new Request.Builder().get().url(stringBuffer.toString()).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFailed(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
Log.i("TAG",result);
//拿到数据开始解析
final Object o = new Gson().fromJson(result, c);
//当前是在子线程,回到主线程中
handler.post(new Runnable() {
@Override
public void run() {
//回调
callBack.onSuccess(o);
}
});
}
});
}
}
俩个接口
public interface CallBack {
void onSuccess(Object o );
void onFailed(Exception e);
}
public interface Iv {
void onSuccess(List<ListBean> list);
void onFiled(Exception e);
}
public class MainActivity extends AppCompatActivity implements Iv{
private ImageView imageview;
private EditText edidtext;
private Button button;
private XRecyclerView xrecyclerview;
private Adapter adapter;
private int i=1;
private List<ListBean> list = new ArrayList<>();
private boolean flag=true;
private Presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//设置可上拉
xrecyclerview.setPullRefreshEnabled(true);
xrecyclerview.setLoadingMoreEnabled(true);
//设置上拉下拉样式
xrecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
xrecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
// 线性布局管理器 VERTICAL默认样式/竖向显示 第三个参数是数据是否到过来显示
LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
//添加布局管理器
xrecyclerview.setLayoutManager(manager);
adapter = new Adapter(MainActivity.this, list,1);
xrecyclerview.setAdapter(adapter);
//设置下拉加载上拉刷新监听
xrecyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
i=1;
list.clear();
loaddata(i);
xrecyclerview.refreshComplete();
}
@Override
public void onLoadMore() {
i++;
loaddata(i);
xrecyclerview.loadMoreComplete();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
i=1;
list.clear();
loaddata(i);
}
});
//图片切换布局的点击事件
imageview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag){
imageview.setImageDrawable(getResources().getDrawable(R.drawable.lv_icon));
GridLayoutManager manager = new GridLayoutManager(MainActivity.this, 2,LinearLayoutManager.VERTICAL,false);
xrecyclerview.setLayoutManager(manager);
adapter = new Adapter(MainActivity.this, list,2);
xrecyclerview.setAdapter(adapter);
flag=false;
}else{
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false);
xrecyclerview.setLayoutManager(manager);
adapter = new Adapter(MainActivity.this, list,1);
xrecyclerview.setAdapter(adapter);
flag=true;
}
}
});
}
//搜索框的实现 和接收p层的数据
public void loaddata(int i){
String str = edidtext.getText().toString().trim();
//搜索关键字
if(str.trim().equals("手机")||str.trim().equals("笔记本")) {
presenter = new Presenter(MainActivity.this, MainActivity.this);
presenter.get(str, i);
}else{
Toast.makeText(MainActivity.this,"请输入正确的信息",Toast.LENGTH_SHORT).show();
}
}
//初始化控件
private void initView() {
imageview = (ImageView)findViewById(R.id.imageView);
edidtext = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
xrecyclerview = (XRecyclerView)findViewById(R.id.xrecyclerview);
}
@Override
public void onSuccess(List<ListBean> lis) {
list.addAll(lis);
adapter.notifyDataSetChanged();
}
@Override
public void onFiled(Exception e) {
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onremove();
}
}