左右联动+自定义View搜索

本文详细介绍了在MVVM架构下如何实现商品分类的展示与关键词搜索功能,通过自定义适配器和使用OkHttp进行网络请求,实现了左右侧商品分类与商品列表的动态加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先创建一个类里面放接口
public class GoodsApi {
public static final String Left_Api=“http://172.17.8.100/small/commodity/v1/findFirstCategory”;
public static final String Right_Api=“http://172.17.8.100/small/commodity/v1/findCommodityByKeyword?page=1&count=10&keyword=”;
}
然后写一个接口里面放成功失败方法
public interface OkHttpUtilsCallBack {
void onSuccess(String result);
void onFilure(String msg);
}
然后将M,V,P层的接口定义在一个接口中 直接调用这个接口中的接口
public interface GoodsContract {

//M层
interface IModle{
    void LeftModle(HashMap<String,String>map, final OkHttpUtilsCallBack okHttpUtilsCallBack);
    void RightModle(HashMap<String,String>map,final OkHttpUtilsCallBack okHttpUtilsCallBack);
}
//V层
interface IView{
    void LeftSuccess(String result);
    void RightSuccess(String msg);
    void LeftError(String msg);
    void RightError(String msg);
}
//P层
abstract class IPresenter{
    public abstract void Leftpresenter(HashMap<String,String>map);
    public abstract void Rightpresenter(HashMap<String,String>map);
}

}

接下来的OkHttp

public class OkHttpUtils {
private final OkHttpClient okHttpClient;
private Handler handler=new Handler();
private static OkHttpUtils okHttpUtils;

//创建私有
private OkHttpUtils(){
    HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .connectTimeout(5,TimeUnit.SECONDS)
            .writeTimeout(5,TimeUnit.SECONDS)
            .readTimeout(5,TimeUnit.SECONDS)
            .build();
}
//单利模式
public static OkHttpUtils getInstance(){
    if (okHttpUtils==null){
        synchronized (OkHttpUtils.class){
            if (okHttpUtils==null){
                okHttpUtils=new OkHttpUtils();
            }
        }
    }
    return okHttpUtils;
}

//doget方法
public void doGet(String url, final OkHttpUtilsCallBack okHttpUtilsCallBack){
    Request request=new Request.Builder()
            .url(url)
            .get()
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    okHttpUtilsCallBack.onFilure("网络异常");
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String resukt = response.body().string();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    okHttpUtilsCallBack.onSuccess(resukt);

                }
            });
        }
    });
}

}

M层

public class GoodsModle implements GoodsContract.IModle {
private Handler handler=new Handler();
private String key;
private String value;
@Override
public void LeftModle(HashMap<String, String> map, final OkHttpUtilsCallBack okHttpUtilsCallBack) {
OkHttpUtils.getInstance().doGet(GoodsApi.Left_Api, new OkHttpUtilsCallBack() {
@Override
public void onSuccess(final String result) {
handler.post(new Runnable() {
@Override
public void run() {
okHttpUtilsCallBack.onSuccess(result);
}
});
}

        @Override
        public void onFilure(String msg) {
            okHttpUtilsCallBack.onFilure(msg);
        }
    });

}

@Override
public void RightModle(HashMap<String, String> map, final OkHttpUtilsCallBack okHttpUtilsCallBack) {

    for (Map.Entry<String,String> p:map.entrySet()){
        key=p.getKey();
        value=p.getValue();
    }
    String s=GoodsApi.Right_Api+value;

    OkHttpUtils.getInstance().doGet(s, new OkHttpUtilsCallBack() {
        @Override
        public void onSuccess(final String result) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    okHttpUtilsCallBack.onSuccess(result);
                }
            });
        }

        @Override
        public void onFilure(final String msg) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    okHttpUtilsCallBack.onFilure(msg);
                }
            });
        }
    });
}

}

P层

public class GoodsPresenter extends GoodsContract.IPresenter {
private GoodsModle goodsModle;
private GoodsContract.IView iView;

public GoodsPresenter(GoodsContract.IView iView){
    this.iView=iView;
    this.goodsModle=new GoodsModle();
}

@Override
public void Leftpresenter(HashMap<String, String> map) {
    goodsModle.LeftModle(map, new OkHttpUtilsCallBack() {
        @Override
        public void onSuccess(String result) {
            if (iView!=null){
                iView.LeftSuccess(result);
            }
        }

        @Override
        public void onFilure(String msg) {
            if (iView!=null){
                iView.RightError(msg);
            }
        }
    });

}

@Override
public void Rightpresenter(HashMap<String, String> map) {
    goodsModle.RightModle(map, new OkHttpUtilsCallBack() {
        @Override
        public void onSuccess(String result) {
            if (iView!=null){
                iView.RightSuccess(result);
            }
        }

        @Override
        public void onFilure(String msg) {
            if (iView!=null){
                iView.RightError(msg);
            }
        }
    });
}

}
接下来就要写适配器了 我们要写两个适配器 一个左边的一个右边的

左边的适配器

左边的适配器里面有一个接口回调 是点击左边条目展示数据用的
public class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.ViewHolder> {
private Context context;
private List<LeftBean.Data> list;

public LeftAdapter(Context context){
    this.context=context;
    this.list=new ArrayList<>();
}

public void setList(List<LeftBean.Data> result){
    if (result!=null){
        this.list=result;
    }
    notifyDataSetChanged();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_left, parent, false);
    ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    LeftBean.Data data = list.get(position);
    holder.name.setText(data.name);
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onClickItemListener.Onclick(list.get(position).name.substring(0,2));
        }
    });
}

@Override
public int getItemCount() {
    return list==null ? 0:list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{

    private final TextView name;

    public ViewHolder(View itemView) {
        super(itemView);
        name=itemView.findViewById(R.id.name);
    }
}

//接口回调
private OnClickItemListener onClickItemListener;

public void setOnClickItemListener(OnClickItemListener onClickItemListener){
    this.onClickItemListener=onClickItemListener;
}

public interface OnClickItemListener{
    void Onclick(String cid);
}

}

右边的适配器

public class RightAdapter extends RecyclerView.Adapter<RightAdapter.RightHolder> {
private Context context;
private List<RightBean.Product> list;

public RightAdapter(Context context){
    this.context=context;
    this.list=new ArrayList<>();
}

@Override
public RightHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_right, parent, false);
    RightHolder rightHolder = new RightHolder(view);
    return rightHolder;
}

@Override
public void onBindViewHolder(RightHolder holder, int position) {
    RightBean.Product product=list.get(position);
    holder.textView.setText(product.getCommodityName());
    Glide.with(context).load(product.getMasterPic()).into(holder.imageView);
}

@Override
public int getItemCount() {
    return list==null ? 0:list.size();
}

public void setRightList(List<RightBean.Product> result){
    if (result!=null){
        this.list=result;
    }
    notifyDataSetChanged();
}

public class RightHolder extends RecyclerView.ViewHolder{

    private final TextView textView;
    private final ImageView imageView;

    public RightHolder(View itemView) {
        super(itemView);
        textView=itemView.findViewById(R.id.name);
        imageView=itemView.findViewById(R.id.iv);
    }
}

}

自定义的View

public class MyView extends LinearLayout {

public Button btn;
public EditText name;

public MyView(Context context) {
    super(context);
}

public MyView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    LayoutInflater.from(context).inflate(R.layout.activity_myview,this,true);
    name=findViewById(R.id.ed_name);
    btn=findViewById(R.id.btn);
}

public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

}
对应的布局
<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
xmlns:app=“http://schemas.android.com/apk/res-auto”>

<EditText
    android:id="@+id/ed_name"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/btn"
    />
<Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="搜索"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toRightOf="@+id/ed_name"
    />

</android.support.constraint.ConstraintLayout>

然后是展示的Activity

public class MainActivity extends AppCompatActivity implements GoodsContract.IView,LeftAdapter.OnClickItemListener {

private RecyclerView rightXr,leftXr;
private MyView views;
private LeftAdapter leftAdapter;
private RightAdapter rightAdapter;
private GoodsPresenter goodsPresenter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //添加适配器
    leftXr=findViewById(R.id.left_xr);
    rightXr=findViewById(R.id.right_xr);
    views=findViewById(R.id.views);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    leftXr.setLayoutManager(linearLayoutManager);

    rightXr.setLayoutManager(new GridLayoutManager(this,3));
    //添加适配器
    leftAdapter = new LeftAdapter(this);
    rightAdapter = new RightAdapter(this);

    //p层
    goodsPresenter = new GoodsPresenter(this);
    goodsPresenter.Leftpresenter(new HashMap<String, String>());

    final HashMap<String,String> hashMap=new HashMap<>();
    hashMap.put("keyword","鞋");
    goodsPresenter.Rightpresenter(hashMap);


    views.btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String s = views.name.getText().toString();
            HashMap<String,String> hashMap1=new HashMap<>();
            hashMap1.put("keywore",s);
            goodsPresenter.Rightpresenter(hashMap1);
        }
    });
}



@Override
public void LeftSuccess(String result) {
  //  Log.e("tag" ,"LeftSuccess == " + result);
    LeftBean leftBean = new Gson().fromJson(result, LeftBean.class);
    if (leftBean!=null){
        leftAdapter = new LeftAdapter(this);
        leftAdapter.setList(leftBean.result);
        leftXr.setAdapter(leftAdapter);
        leftAdapter.setOnClickItemListener(this);
    }
}

@Override
public void RightSuccess(String msg) {
  //  Log.e("tag" ,"RightSuccess == " + msg);
    RightBean rightBean = new Gson().fromJson(msg, RightBean.class);
    if (rightBean!=null){
        rightAdapter = new RightAdapter(this);
        rightAdapter.setRightList(rightBean.getResult());
        rightXr.setAdapter(rightAdapter);
    }

}

@Override
public void LeftError(String msg) {

}

@Override
public void RightError(String msg) {

}
@Override
public void Onclick(String cid) {
    getLeft(cid);
}

public void getLeft(String cid){
    HashMap<String,String> hashMap=new HashMap<>();
    hashMap.put("keywork",cid);
    goodsPresenter.Rightpresenter(hashMap);
}

}
对应的布局文件
展示的布局文件

<com.example.erjileibiao.view.MyView
    android:id="@+id/views"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    ></com.example.erjileibiao.view.MyView>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal"
    android:layout_weight="9"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/left_xr"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        ></android.support.v7.widget.RecyclerView>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/right_xr"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="6"
        ></android.support.v7.widget.RecyclerView>
</LinearLayout>
**左边的布局文件**
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp">


    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="商品分类"
        android:textSize="20dp"
        />
</LinearLayout>
**右边的布局文件**
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:layout_gravity="center"
        android:id="@+id/iv"
        android:src="@mipmap/ic_launcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:gravity="center"
        android:id="@+id/name"
        android:text="手机"
        android:layout_margin="5dp"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值