Android ListView带图片复写

嘿,今天的你过的还好吗,今天分享复写ListView,方便复盘用

最开始还是需要xml文件

<ListView
            android:id="@+id/commodity_news_lv"
            android:layout_width="match_parent"
            android:layout_below="@id/commodity_ll"
            android:layout_height="match_parent"/>

复写一个bean

package cn.ryanliu.mall.bean;

public class CommodityBean {
        private Integer commodityImg;
        private String tradename;
        private String unitprice;
        private String commodityorigin;
        private String testing;

        public Integer getCommodityImg() {
                return commodityImg;
        }

        public void setCommodityImg(Integer commodityImg) {
                this.commodityImg = commodityImg;
        }

        public String getTradename() {
                return tradename;
        }

        public void setTradename(String tradename) {
                this.tradename = tradename;
        }

        public String getUnitprice() {
                return unitprice;
        }

        public void setUnitprice(String unitprice) {
                this.unitprice = unitprice;
        }

        public String getCommodityorigin() {
                return commodityorigin;
        }

        public void setCommodityorigin(String commodityorigin) {
                this.commodityorigin = commodityorigin;
        }

        public String getTesting() {
                return testing;
        }

        public void setTesting(String testing) {
                this.testing = testing;
        }
}

然后写一个listview布局文件

<?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">

    <LinearLayout
        android:id="@+id/commodity_news_ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/commodity_ll"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/commodityinformation"
            android:paddingLeft="70dp"
            android:layout_gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/commodityinformation" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_width="70dp"
                android:layout_height="wrap_content"
                android:text="@string/tradename" />

            <TextView
                android:id="@+id/trade_name_tv"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="白菜" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_width="70dp"
                android:layout_height="wrap_content"
                android:text="@string/unitprice" />

            <TextView
                android:id="@+id/unit_price_tv"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="2" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_width="70dp"
                android:layout_height="wrap_content"
                android:text="@string/commodityorigin" />

            <TextView
                android:id="@+id/commodity_origin_tv"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="山东" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_marginLeft="5dp"
                android:layout_width="70dp"
                android:layout_height="wrap_content"
                android:text="@string/testing" />

            <TextView
                android:id="@+id/testing_tv"
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="合格" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

再来一个复写的adapter

package cn.ryanliu.mall.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

import cn.ryanliu.mall.R;
import cn.ryanliu.mall.bean.CommodityBean;

public class CommodityAdapter extends ArrayAdapter<CommodityBean> {
    private Context context;
    private int resource;
    private List<CommodityBean> commodityBeanList;
    public CommodityAdapter(@NonNull Context context, int resource , List<CommodityBean> commodityBeanList) {
        super(context, resource);
        this.context = context;
        this.resource = resource;
        this .commodityBeanList = commodityBeanList;
    }

    @Override
    public int getCount() {
        return commodityBeanList.size();
    }

    @Nullable
    @Override
    public CommodityBean getItem(int position) {
        return commodityBeanList.get(position);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView==null){
            convertView= LayoutInflater.from(this.getContext()).inflate(resource,parent,false);
        }
        TextView tradename,unitprice,commodityorigin,testing;
        ImageView commodityinformation;

        tradename = convertView.findViewById(R.id.trade_name_tv);
        unitprice = convertView.findViewById(R.id.unit_price_tv);
        commodityorigin = convertView.findViewById(R.id.commodity_origin_tv);
        testing = convertView.findViewById(R.id.testing_tv);
        commodityinformation = convertView.findViewById(R.id.commodityinformation);

        tradename.setText(commodityBeanList.get(position).getTradename());
        unitprice.setText(commodityBeanList.get(position).getUnitprice());
        commodityorigin.setText(commodityBeanList.get(position).getCommodityorigin());
        testing.setText(commodityBeanList.get(position).getTesting());
        commodityinformation.setImageResource(commodityBeanList.get(position).getCommodityImg());

        return convertView;
    }
}

最后在Activity中引用

package cn.ryanliu.mall;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.ryanliu.mall.adapter.CommodityAdapter;
import cn.ryanliu.mall.bean.CommodityBean;
import cn.ryanliu.mall.util.MyListView;
import cn.ryanliu.mall.util.okHttpUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CommodityActivity extends AppCompatActivity {
    private TextView business_name_tv,stall_number_tv,order_number_tv,market_unit_tv,market_phone_tv,supervision_unit_tv,supervision_phone_tv;
    private MyListView commodity_news_lv;
    private Handler handler;

    private CommodityAdapter mCommodityAdapter;
    private List<CommodityBean> mCommodityList;

    private String OutletsName;
    private String FactoryName;
    private String PhoneNum;
    private String Cname;
    private String PhoneNumTow;
    private String OutTradeNo;
    private String OutletsNumber;

    private Integer[] img = new Integer[]{R.drawable.commodityinformation,R.drawable.searchbackground};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    //商家名称
                    business_name_tv.setText(OutletsName);
                    //市场单位
                    market_unit_tv.setText(FactoryName);
                    //市场电话
                    market_phone_tv.setText(PhoneNum);
                    //监督单位
                    supervision_unit_tv.setText(Cname);
                    //监督单位电话
                    supervision_phone_tv.setText(PhoneNumTow);
                    //摊位号
                    stall_number_tv.setText(OutletsNumber);
                    order_number_tv.setText(OutTradeNo);
                    mCommodityAdapter.notifyDataSetChanged();

                }
            }
        };
        //沉浸式状态栏
        statusbar();
        //实例化
        initView();
        //数据层
        datalayer();
        //网络层
        netWork();
    }

    private void netWork() {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        ;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("OutTradeNo", "...");
            jsonObject.put("Type", "...");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsonObject));
        okHttpUtil.postOkhttpRequest("url", requestBody, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("ryanliu", "onFailure: " + e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String reposes = response.body().string();
                Log.i("ryanliu", reposes + "");
                try {
                    JSONObject jsonObject = new JSONObject(reposes);
                    String data = jsonObject.optString("data");
                    JSONObject jsonObject1 = new JSONObject(data);
                    String GoodsList = jsonObject1.optString("GoodsList");
                    String outlets = jsonObject1.optString("outlets");
                    String factory = jsonObject1.optString("factory");
                    JSONObject outlet = new JSONObject(outlets);
                    JSONObject factorys = new JSONObject(factory);
                    OutTradeNo = jsonObject1.getString("OutTradeNo");
                    OutletsName = outlet.getString("OutletsName");
                    OutletsNumber = outlet.getString("OutletsNumber");
                    FactoryName = factorys.getString("FactoryName");
                    PhoneNum = factorys.getString("PhoneNum");
                    Cname = factorys.getString("Cname");
                    PhoneNumTow = factorys.getString("PhoneNumTow");
                    JSONArray jsonArray = new JSONArray(GoodsList);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        jsonObject1 = new JSONObject(jsonArray.get(i).toString());
                        CommodityBean b = new CommodityBean();
                        b.setUnitprice(jsonObject1.getString("UnitPrice"));
                        b.setTradename(jsonObject1.getString("GoodsName"));
                        b.setTesting(jsonObject1.getString("Checks"));
//                        b.setCommodityImg(jsonObject1.getInt("ThumbnailPicFileID"));
                        b.setCommodityorigin(jsonObject1.getString("Origin"));
                        b.setCommodityImg(img[i]);
                        mCommodityList.add(b);
                    }
                    handler.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void datalayer() {
        //取得从上一个Activity当中传递过来的Intent对象
        Intent intent = getIntent();
        //从Intent当中根据key取得value
        if (intent != null) {
            String code_value = intent.getStringExtra("code_et");
            Log.i("it520", "initView: " + code_value);
        }
        mCommodityList = new ArrayList<>();
        mCommodityAdapter = new CommodityAdapter(this,R.layout.listview_commodity_news,mCommodityList);
        commodity_news_lv.setAdapter(mCommodityAdapter);
    }

    private void initView() {
        commodity_news_lv = findViewById(R.id.commodity_news_lv);
        business_name_tv = findViewById(R.id.business_name_tv);
        stall_number_tv = findViewById(R.id.stall_number_tv);
        order_number_tv = findViewById(R.id.order_number_tv);
        market_unit_tv = findViewById(R.id.market_unit_tv);
        market_phone_tv = findViewById(R.id.market_phone_tv);
        supervision_unit_tv = findViewById(R.id.supervision_unit_tv);
        supervision_phone_tv = findViewById(R.id.supervision_phone_tv);
    }

    private void statusbar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //如果>=4.4才支持沉浸式
            //显示上面的导航栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //显示下面的导航键
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //隐藏状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            //显示状态栏
//            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    //页面跳转封装方法
    public static void statr(Context context) {
        Intent intent = new Intent(context, CommodityActivity.class);
        context.startActivity(intent);
    }
}

方便自己最后复盘使用

没更新动态或者频繁更新动态的时候都是在认真生活

推荐阅读更多精彩内容