技术篇-android ListView网络图片下载文件缓存

阿里 阅读:1106 2021-04-01 10:27:40 评论:0

第一步:编写文件缓存的相关方法,关于Software缓存类在网上可以搜索到相关的资料(文件缓存工具类)

public class AsyncImageLoader {

 // SoftReference是软引用,是为了更好的为了系统回收变量
 private HashMap<String, SoftReference<Bitmap>> imageCache;

 public AsyncImageLoader() {
  imageCache = new HashMap<String, SoftReference<Bitmap>>();
 }

 // 第一种方法
 // public Bitmap loadBitmap(final ImageView imageView, final String
 // imageURL, final ImageCallBack imageCallBack)
 // {
 // //在内存缓存中,则返回Bitmap对象
 // if(imageCache.containsKey(imageURL))
 // {
 // SoftReference<Bitmap> reference = imageCache.get(imageURL);
 // Bitmap bitmap = reference.get();
 // if(bitmap != null)
 // {
 // return bitmap;
 // }
 // }
 // else
 // {
 // /**
 // * 加上一个对本地缓存的查找
 // */
 // //截取上传的文件名称
 // String bitmapName = imageURL.substring(imageURL.lastIndexOf("/") + 1);
 // //文件的存放地址
 // File cacheDir = new File("/mnt/sdcard/test/");
 // // if(!cacheDir.exists()){
 // // cacheDir.mkdirs();
 // // }
 // //文件数组
 // File[] cacheFiles =cacheDir.listFiles();
 // if(cacheFiles!=null){
 // int i = 0;
 // //判定文件数组是否包含存在的图片文件
 // for(; i<cacheFiles.length; i++)
 // {
 // if(bitmapName.equals(cacheFiles[i].getName()))
 // {
 // break;
 // }
 // }
 // //如果在文件数组中存在相关的图片资源(读取图片)
 // if(i < cacheFiles.length)
 // {
 // return BitmapFactory.decodeFile("/mnt/sdcard/test/" + bitmapName);
 // }
 // }
 //
 // }
 // //启动主线程(实时的界面更新工作)
 // final Handler handler = new Handler()
 // {
 // /* (non-Javadoc)
 // * @see android.os.Handler#handleMessage(android.os.Message)
 // */
 // @Override
 // public void handleMessage(Message msg)
 // {
 // // TODO Auto-generated method stub
 // imageCallBack.imageLoad(imageView, (Bitmap)msg.obj,imageURL);
 // }
 // };
 //
 // //如果不在内存缓存中,也不在本地(被jvm回收掉),则开启线程下载图片
 // new Thread()
 // {
 // /* (non-Javadoc)
 // * @see java.lang.Thread#run()
 // */
 // @Override
 // public void run()
 // {
 // // TODO Auto-generated method stub
 // InputStream bitmapIs;
 //
 // bitmapIs = ImageUtil.getRequest(imageURL);
 // Bitmap bitmap = BitmapFactory.decodeStream(bitmapIs);
 // //添加下载资源的(软应用)
 // imageCache.put(imageURL, new SoftReference<Bitmap>(bitmap));
 // Message msg = handler.obtainMessage(0, bitmap);
 // handler.sendMessage(msg);
 //
 // //创建文件保存下载的图片
 // File dir = new File("/mnt/sdcard/test/");
 // if(!dir.exists())
 // {
 // dir.mkdirs();
 // }
 // //文件的命名规范
 // File bitmapFile = new File("/mnt/sdcard/test/" +
 // imageURL.substring(imageURL.lastIndexOf("/") + 1));
 //
 // if(!bitmapFile.exists())
 // {
 // try
 // {
 // bitmapFile.createNewFile();
 // }
 // catch (IOException e)
 // {
 // // TODO Auto-generated catch block
 // e.printStackTrace();
 // }
 // }
 // // BufferedOutputStream bos = new BufferedOutputStream(new
 // FileOutputStream(bitmapFile));
 // //bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
 // // bos.flush();
 // // bos.close();
 //
 //
 // FileOutputStream fos;
 // try
 // {
 // fos = new FileOutputStream(bitmapFile);
 // bitmap.compress(Bitmap.CompressFormat.JPEG,
 // 100, fos);
 // fos.close();
 // }
 // catch (FileNotFoundException e)
 // {
 // // TODO Auto-generated catch block
 // e.printStackTrace();
 // }
 // catch (IOException e)
 // {
 // // TODO Auto-generated catch block
 // e.printStackTrace();
 // }
 // }
 //
 // }.start();
 //
 // return null;
 // }

 // /**
 // * 回调接口
 // * @author onerain
 // *
 // */
 // public interface ImageCallBack
 // {
 // public void imageLoad(ImageView imageView, Bitmap bitmap,String target);
 // }
 // 第二种方法
 // 异步加载图片。
 public Bitmap loadDrawable(final ImageView imageView,
   final String imageUrl, final ImageCallback imageCallback) {
  // 判断软引用是否存在这张图片的路劲,如果有的话,则直接返回软引用中的图片,进行返回。
  // if (imageCache.containsKey(imageUrl)) {
  //
  // SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
  //
  // Bitmap drawable = softReference.get();
  //
  // if (drawable != null) {
  //
  // return drawable;
  //
  // }
  //
  // }if {
  // 添加文件存储缓存(判断下载的图片是否存在图片)
  // 截取上传的文件名称
  String drawableName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

  // SD卡创建legouimages文件夹
  File Dir = Environment.getExternalStorageDirectory();
  String path = Dir.getPath() + "/legouimages";
  File CardDir = new File(path);
  if (!CardDir.exists()) {
   CardDir.mkdirs();
  }

  // 遍历文件中的图片资源
  File[] cacheFiles = CardDir.listFiles();
  int i = 0;
  for (; i < cacheFiles.length; i++) {
   // String str=cacheFiles[i].getPath();
   if (drawableName.equals(cacheFiles[i].getName())) {
    return BitmapFactory.decodeFile(cacheFiles[i].getPath());

   }
  }
  // if (i < cacheFiles.length) {
  //
  // }

  // }
  // 线程下载图片资源的回调
  final Handler handler = new Handler() {

   public void handleMessage(Message message) {
    // 完成后,进行回调,参数1:返回的图片Drawable对象,参数2:图片的服务器路劲(imageView的TAG标识。)
    imageCallback.imageLoaded((Bitmap) message.obj);

   }
  };
  // 如果图片在软引用中不存在,则启动子线程进行图片下载。
  new Thread() {
   @Override
   public void run() {
    InputStream bitmapIs = getStreamFromURL(imageUrl);
    Bitmap bitmap = BitmapFactory.decodeStream(bitmapIs);

    // Drawable drawable = loadImageFromUrl(imageUrl);

    imageCache.put(imageUrl, new SoftReference<Bitmap>(bitmap));

    Message message = handler.obtainMessage(0, bitmap);
    handler.sendMessage(message);

    File d = Environment.getExternalStorageDirectory();
    String p = d.getPath() + "/legouimages";
    File dir = new File(p);

    // if (!dir.exists()) {
    // dir.mkdirs();
    // }
    File bitmapFile = new File(p + "/"
      + imageUrl.substring(imageUrl.lastIndexOf("/") + 1));

    if (!bitmapFile.exists()) {
     try {
      bitmapFile.createNewFile();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    FileOutputStream fos;
    try {
     fos = new FileOutputStream(bitmapFile);
     bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);

     fos.close();
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

   }

  }.start();

  return null;

 }

 // 图片下载
 public static InputStream getStreamFromURL(String url) {
  URL m;
  InputStream i = null;
  try {
   // 图片访问地址
   m = new URL(url);
   // 获取图片的字节流。
   i = m.openStream();
  } catch (MalformedURLException e1) {
   e1.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return i;
 }

 // 当图片线程下载成功后,将调用该函数在getView方法中,进行回调,更新到ListView中的imageView。
 public interface ImageCallback {
  public void imageLoaded(Bitmap bitmap);
 }

}

 

第二步:ListView图片下载与展示:

public class JinRilgActivity extends Activity {

 // 屏幕的width
 private int mScreenWidth;
 // 屏幕的height
 private int mScreenHeight;
 // PopupWindow的width
 private int mPopupWindowWidth;
 // PopupWindow的height
 private int mPopupWindowHeight;
 // 分类的linearlayout
 LinearLayout jinrilg_fenlei_lin;
 // 菜单项item的linearLayout。
 LinearLayout jinrilg_menu_msfl_lin;
 LinearLayout jinrilg_menu_ssgw_lin;
 LinearLayout jinrilg_menu_fzxb_lin;
 LinearLayout jinrilg_menu_shjj_lin;
 LinearLayout jinrilg_menu_qt_lin;
 // 用于保存当前所在菜单的位置
 static int MENU_INDEX = 0;

 PopupWindow mPopupWindow;

 // 相关工具类和数据源
 List<JinriLg> lists = new ArrayList<JinriLg>();
 // 美食天下数据
 List<JinriLg> lists1 = new ArrayList<JinriLg>();
 private AsyncImageLoader imageloader;
 // 相关组件
 private ListView listview;
 // 创建进度对话框
 private ProgressDialog processdialog;
 // 创建进度对话框(美食天下)
 private ProgressDialog processdialog1;

 public void params() {
  // 四个文本框组件(相关组件)
  final TextView wdlg = (TextView) findViewById(R.id.jydg);
  wdlg.setBackgroundResource(R.drawable.bj1);
  // 今日乐购按钮

  LinearLayout jirianniu = (LinearLayout) findViewById(R.id.jinrilegou);
  jirianniu.setBackgroundResource(R.drawable.bj1);

  jirianniu.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
   }

  });
  // 我的乐购
  LinearLayout wodelegou = (LinearLayout) findViewById(R.id.wodelegou);
  wodelegou.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Intent intent = new Intent(JinRilgActivity.this, MyLegou.class);
    startActivity(intent);
    JinRilgActivity.this.finish();
   }

  });

  // 导购
  LinearLayout daogou = (LinearLayout) findViewById(R.id.daogou);
  daogou.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Intent intent = new Intent(JinRilgActivity.this,
      DaogouActivity.class);
    startActivity(intent);
    JinRilgActivity.this.finish();

   }

  });

  // 更多
  LinearLayout gengduo = (LinearLayout) findViewById(R.id.gengduo);
  gengduo.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    Intent intent = new Intent(JinRilgActivity.this,
      GengduoActivity.class);
    startActivity(intent);
    JinRilgActivity.this.finish();

   }

  });

 }

 // 主线程
 private Handler handler = new Handler() {

  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   // 解析相关信息
   switch (msg.what) {
   case 0:
    Bundle bundle = msg.getData();
    String json = bundle.getString("json");
    findJinRiLeGou(json);
    break;
   // 美食天下
   case 1:
    Bundle b1 = msg.getData();
    String j1 = b1.getString("json");
    findJinRiLeGou1(j1);
    break;
   }
  }

 };

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // 自定义窗口标题的样式 注意顺序
  setContentView(R.layout.main);
  JinRilgActivity.this.getWindow().setFeatureInt(
    Window.FEATURE_CUSTOM_TITLE, R.layout.mainmenutitle);// 注意顺序

  // 添加今日乐购Activity
  ApplicationBase.getinstace().addActivity(JinRilgActivity.this);
  // 对话框实例化
  processdialog = new ProgressDialog(JinRilgActivity.this);
  processdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  processdialog.setMessage("图片资源加载当中...");
  processdialog.setIndeterminate(false);
  processdialog.setCancelable(true);
  processdialog.setButton("取消", new DialogInterface.OnClickListener() {

   @Override
   public void onClick(DialogInterface arg0, int arg1) {
    processdialog.dismiss();

   }

  });
  processdialog.show();
  // 相关工具类(实例化)
  imageloader = new AsyncImageLoader();
  initParmas();
  // 组件的相关初始化方法
  init();
  // 自定义标题栏的监听事件
  params();
  // ListView 设置监听事件
  listview.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapter, View view,
     int position, long arg3) {
    // 跳转到商品详情界面(相关参数的传递)
    Intent intent = new Intent(JinRilgActivity.this,
      ShanpinxqActivity.class);
    Bundle extras = new Bundle();
    JinriLg jinrilg = lists.get(position);
    extras.putSerializable("jinrilegou", jinrilg);
    intent.putExtras(extras);
    startActivity(intent);
   }
  });
 }

 /**
  * 用于请求查询数据。这里是静态的, 必须通过线程访问后台服务进行查询, 并在消息队列中进行处理显示以及加载数据到ListView
  */
 public void findJinRiLeGou(String json) {
  try {
   JSONArray jsonarray = new JSONArray(json);
   if (jsonarray.length() > 0) {
    // 相关信息的循环遍历
    for (int i = 0; i < jsonarray.length(); i++) {
     JSONObject object = jsonarray.getJSONObject(i);
     // 商品编号
     String daogou_bh = object.getString("goodId");
     // 商品标题
     String daogou_spbt = object.getString("goodName");
     // 商品原价格
     double daogou_spjg = object.getDouble("price");
     // 商品折扣
     double daogou_spzk = object.getDouble("discount");
     // 商品购买人数
     int daogou_gmrs = object.getInt("persons");
     // 商品优惠时间
     String daogou_yhsj = object.getString("endtime");
     // 商品图片路径
     String daogou_tpsp = object.getString("imgpath");
     // 商品现在价格
     double daogou_xzjg = object.getDouble("newprice");
     // 商品介绍
     String daogou_spjs = object.getString("intro");
     // 商家信息(待检查)
     // String daogou_sjxx=object.getString("");

     // 相关信息的存储工作
     JinriLg jinrilg = new JinriLg();
     // 商品购买人数
     jinrilg.setNumber(daogou_gmrs);
     // 商品名称
     jinrilg.setCommodity(daogou_spbt);
     // 商品销售时间
     jinrilg.setTime(daogou_yhsj);
     // 商品原价格
     jinrilg.setProduct_list(daogou_spjg);
     // 商品折扣
     jinrilg.setMerchandise_discounts(daogou_spzk);
     // 商品现价
     jinrilg.setNow_price(daogou_xzjg);
     // 商品图片
     jinrilg.setImageurl(Settings.service_path
       + Settings.file_path + daogou_tpsp);
     // 商品介绍
     jinrilg.setIntroduction(daogou_spjs);
     // 添加商品编号
     jinrilg.setBianhao(daogou_bh);
     // 相关数据信息添加
     lists.add(jinrilg);
    }
   } else {
    // 相关提示
    Toast.makeText(JinRilgActivity.this, "温馨提示:无商品信息...",
      Toast.LENGTH_LONG).show();
    return;
   }
   // 相关组件的初始化工作
   MyAdapter adapter = new MyAdapter(lists, imageloader,
     JinRilgActivity.this);
   listview.setAdapter(adapter);
   // 关闭进度对话框
   processdialog.cancel();

  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 /*
  * 初始化工作
  */
 public void initParmas() {
  // 点击分类按钮触发事件
  jinrilg_fenlei_lin = (LinearLayout) findViewById(R.id.jinrilg_fenlei);
  jinrilg_fenlei_lin.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    if (mPopupWindow == null) {
     // 获得实例化PopupWindow对象
     getPopupWindowInstance();
     // 显示Window,在提供的组件下方显示,并设置X,和Y的偏移。
     mPopupWindow.showAsDropDown(v, 0, -80);
    }
   }
  });

 }

 // 组件初始化的相关方法
 public void init() {
  // ListView组件初始化
  listview = (ListView) findViewById(R.id.list);

  final JinRilg lg = new JinRilg();
  new Thread() {
   @Override
   public void run() {
    handler.postDelayed(lg, 1000);
   }
  }.start();
 }

 public class ViewHolder {
  // 修改的相关代码
  private View baseView;

  private TextView title_textview; // 标题
  private TextView jianjie_textview;// 简介
  private TextView xianjia_textview;// 现价
  private TextView yuanjia_textview;// 原价
  private TextView zhekou_textview;// 折扣
  private TextView renshu_textview;// 人数
  private TextView shijian_textview;// 时间
  private ImageView tupian_imageview;// 图片

  // 修改相关代码
  public ViewHolder(View baseView) {
   super();
   this.baseView = baseView;
  }

  public TextView get_title_textview() {
   title_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_shangpinbt);
   return title_textview;
  }

  public TextView get_jianjie_textview() {
   jianjie_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_shangpinjs);
   return jianjie_textview;
  }

  public TextView get_xianjia_textview() {
   xianjia_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_xianjia);
   return xianjia_textview;
  }

  public TextView get_yuanjia_textview() {
   yuanjia_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_yuanjia);
   return yuanjia_textview;
  }

  public TextView get_zhekou_textview() {
   zhekou_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_zhekou);
   return zhekou_textview;
  }

  public TextView get_renshu_textview() {
   renshu_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_goumairs);
   return renshu_textview;
  }

  public TextView get_shijian_textview() {
   shijian_textview = (TextView) baseView
     .findViewById(R.id.jinrilg_youxiaosj);
   return shijian_textview;
  }

  public ImageView get_tupian_imageview() {
   tupian_imageview = (ImageView) baseView
     .findViewById(R.id.jinrilg_shangpintp);
   return tupian_imageview;
  }

 }

 class MyAdapter extends BaseAdapter {

  private LayoutInflater inflater;
  private List<JinriLg> lists;
  private AsyncImageLoader imageloader;
  private Context context;

  public MyAdapter(List<JinriLg> lists, AsyncImageLoader imageloader,
    Context context) {
   super();
   this.lists = lists;
   this.imageloader = imageloader;
   this.context = context;

  }

  @Override
  public int getCount() {
   // TODO Auto-generated method stub
   return lists.size();
  }

  @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
   return lists.get(position);
  }

  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return 0;
  }

  @Override
  public View getView(final int position, View convertView,
    ViewGroup parent) {

   final ViewHolder holder;
   if (convertView == null) {
    LayoutInflater inflater = LayoutInflater.from(context);
    convertView = inflater.inflate(R.layout.jinrilg_textview, null);
    holder = new ViewHolder(convertView);
    // 设置标识
    convertView.setTag(holder);

   } else {
    holder = (ViewHolder) convertView.getTag();
   }

   // 代码注销(第一种方法)
   // //new ViewHolder();
   // holder.renshu_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_goumairs);
   // holder.title_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_shangpinbt);
   // holder.jianjie_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_shangpinjs);
   // holder.xianjia_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_xianjia);
   // holder.shijian_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_youxiaosj);
   // holder.yuanjia_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_yuanjia);
   // holder.zhekou_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_zhekou);
   // holder.zhekou_textview =
   // (TextView)convertView.findViewById(R.id.jinrilg_zhekou);
   //
   // holder.tupian_imageview =
   // (ImageView)convertView.findViewById(R.id.jinrilg_shangpintp);

   // 商品名称
   holder.get_title_textview().setText(
     lists.get(position).getCommodity());
   // holder.title_textview.setText(lists.get(position).getCommodity());
   // 商品介绍
   holder.get_jianjie_textview().setText(
     lists.get(position).getIntroduction());
   // holder.jianjie_textview.setText(lists.get(position).getIntroduction());
   // 商品现价
   holder.get_xianjia_textview().setText(
     "¥" + lists.get(position).getNow_price() + "/");
   // holder.xianjia_textview.setText("¥"+lists.get(position).getNow_price()+"/");
   // 商品销售时间
   holder.get_shijian_textview()
     .setText(lists.get(position).getTime());
   // holder.shijian_textview.setText(lists.get(position).getTime());
   // holder.yuanjia_textview.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
   // 商品原价
   holder.get_yuanjia_textview().setText(
     "¥" + lists.get(position).getProduct_list() + "");
   // holder.yuanjia_textview.setText("¥"+lists.get(position).getProduct_list()+"");
   // 商品折扣
   holder.get_zhekou_textview().setText(
     "(" + lists.get(position).getMerchandise_discounts() * 10.0
       + "折)");
   // holder.zhekou_textview.setText("("+lists.get(position).getMerchandise_discounts()*10+"折)");
   // 商品购买人数
   holder.get_renshu_textview().setText(
     "" + lists.get(position).getNumber());
   // holder.renshu_textview.setText(""+lists.get(position).getNumber());

   // 相关图片加载(图片设置标记)
   String target = lists.get(position).getImageurl();
   final String str = target.substring(target.lastIndexOf("/") + 1);
   // 获得组件
   final ImageView imageviews = holder.get_tupian_imageview();
   // 将图片组件设置服务器图片路劲的标识(解决图片乱加载的现象)
   imageviews.setTag(str);

   // 异步加载图片
   Bitmap drawable = imageloader.loadDrawable(imageviews, target,
     new ImageCallback() {

      @Override
      // //成功后进行回调,处理UI。参数1:返回请求的图片资源,参数2:图片服务器路劲(起组件标识作用)
      // public void imageLoaded(
      // Drawable imageDrawable,
      // String imageUrl) {
      // //根据图片的网络地址做为标识,来查询相应item中的imageView,主要起到一个引用作用。
      // ImageView i=(ImageView)
      // imageview.findViewWithTag(imageUrl);
      // //如果找到对应的ImageView,那就加载相关图片资源。
      // if(i!=null){
      // //如果加载的图片存在,那么就将图片引用到ImageView,否则引用默认图片。
      // if(imageDrawable!=null){
      // i.setImageDrawable(imageDrawable);
      // }
      // else{
      // i.setImageResource(R.drawable.bj3);
      // }
      // }
      // }
      public void imageLoaded(Bitmap bitmap) {
       // TODO Auto-generated method stub
       // imageView.setImageBitmap(bitmap);
       // if(target!=null){
       // imageView=holder.get_tupian_imageview();

       // 获得标记的ImageView
       ImageView imageView = (ImageView) imageviews
         .findViewWithTag(str);

       // if(bitmap==null){
       // imageView.setImageResource(R.drawable.bj3);
       // }else{
       // imageView.setImageBitmap(bitmap);
       // }
       // 判断imageView 是否实例化
       if (imageView == null) {
        return;
       } else {
        imageView.setImageBitmap(bitmap);
       }

      }

     });
   // 当线程还在访问图片时,先暂时用默认图片来代替。
   if (drawable == null) {
    imageviews.setImageResource(R.drawable.bj3);
   }
   // 否则返回软引用中的图片。
   else {
    imageviews.setImageBitmap(drawable);
   }

   // //Item跳转
   // convertView.setOnClickListener(new OnClickListener(){
   // @Override
   // public void onClick(View v) {
   // //跳转到商品详情界面(相关参数的传递)
   // Intent intent=new
   // Intent(JinRilgActivity.this,ShanpinxqActivity.class);
   //
   // startActivity(intent);
   // JinRilgActivity.this.finish();
   // }
   // });

   return convertView;
  }
 }

 // 实例化窗口方法
 public void getPopupWindowInstance() {
  LayoutInflater layoutInflater = LayoutInflater.from(this);
  // 获取分类菜单的组件
  View popupWindow = layoutInflater.inflate(R.layout.fenlei_menu, null);
  jinrilg_menu_msfl_lin = (LinearLayout) popupWindow
    .findViewById(R.id.jinrilg_menu_msfl_lin);
  jinrilg_menu_ssgw_lin = (LinearLayout) popupWindow
    .findViewById(R.id.jinrilg_menu_ssgw_lin);
  jinrilg_menu_fzxb_lin = (LinearLayout) popupWindow
    .findViewById(R.id.jinrilg_menu_fzxb_lin);
  jinrilg_menu_shjj_lin = (LinearLayout) popupWindow
    .findViewById(R.id.jinrilg_menu_shjj_lin);
  jinrilg_menu_qt_lin = (LinearLayout) popupWindow
    .findViewById(R.id.jinrilg_menu_qt_lin);
  // 控制点击的显示和隐藏
  jinrilg_menu_msfl_lin.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // 记录上一次选中的菜单的标识位
    MENU_INDEX = 1;
    // 设置点击背景

    processdialog1 = new ProgressDialog(JinRilgActivity.this);
    processdialog1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    processdialog1.setMessage("图片资源加载当中...");
    processdialog1.setIndeterminate(false);
    processdialog1.setCancelable(false);
    processdialog1.setButton("取消",
      new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface arg0, int arg1) {
        processdialog1.dismiss();
        // JinRilgActivity.this.finish();
       }
      });
    processdialog1.show();

    final JinRilg1 lg1 = new JinRilg1("1");
    new Thread() {
     @Override
     public void run() {
      handler.postDelayed(lg1, 1000);
     }
    }.start();

    jinrilg_menu_msfl_lin
      .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
    jinrilg_menu_ssgw_lin.setBackgroundDrawable(null);
    jinrilg_menu_fzxb_lin.setBackgroundDrawable(null);
    jinrilg_menu_shjj_lin.setBackgroundDrawable(null);
    jinrilg_menu_qt_lin.setBackgroundDrawable(null);

    // //添加相关线程
    // //对话框实例化
    // processdialog1 = new ProgressDialog(JinRilgActivity.this);
    // processdialog1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    // processdialog1.setMessage("图片资源加载当中...");
    // processdialog1.setIndeterminate(false);
    // processdialog1.setCancelable(true);
    // processdialog1.setButton("取消", new
    // DialogInterface.OnClickListener(){
    //
    // @Override
    // public void onClick(DialogInterface arg0, int arg1) {
    // processdialog1.dismiss();
    // JinRilgActivity.this.finish();
    //
    // }
    //
    // });
    // processdialog1.show();

    // final JinRilg1 lg1=new JinRilg1();
    // new Thread(){
    // @Override
    // public void run() {
    // handler.postDelayed(lg1, 1000);
    // }
    // }.start();

   }
  });
  jinrilg_menu_ssgw_lin.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    MENU_INDEX = 2;
    // 设置点击背景

    processdialog1 = new ProgressDialog(JinRilgActivity.this);
    processdialog1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    processdialog1.setMessage("图片资源加载当中...");
    processdialog1.setIndeterminate(false);
    processdialog1.setCancelable(false);
    processdialog1.setButton("取消",
      new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface arg0, int arg1) {
        processdialog1.dismiss();
        // JinRilgActivity.this.finish();
       }
      });
    processdialog1.show();

    final JinRilg1 lg2 = new JinRilg1("2");
    new Thread() {
     @Override
     public void run() {
      handler.postDelayed(lg2, 1000);
     }
    }.start();

    jinrilg_menu_ssgw_lin
      .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
    jinrilg_menu_msfl_lin.setBackgroundDrawable(null);
    jinrilg_menu_fzxb_lin.setBackgroundDrawable(null);
    jinrilg_menu_shjj_lin.setBackgroundDrawable(null);
    jinrilg_menu_qt_lin.setBackgroundDrawable(null);

   }
  });
  jinrilg_menu_fzxb_lin.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    MENU_INDEX = 3;

    processdialog1 = new ProgressDialog(JinRilgActivity.this);
    processdialog1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    processdialog1.setMessage("图片资源加载当中...");
    processdialog1.setIndeterminate(false);
    processdialog1.setCancelable(false);
    processdialog1.setButton("取消",
      new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface arg0, int arg1) {
        processdialog1.dismiss();
        // JinRilgActivity.this.finish();
       }
      });
    processdialog1.show();

    final JinRilg1 lg3 = new JinRilg1("3");
    new Thread() {
     @Override
     public void run() {
      handler.postDelayed(lg3, 1000);
     }
    }.start();

    jinrilg_menu_fzxb_lin
      .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
    jinrilg_menu_msfl_lin.setBackgroundDrawable(null);
    jinrilg_menu_ssgw_lin.setBackgroundDrawable(null);
    jinrilg_menu_shjj_lin.setBackgroundDrawable(null);
    jinrilg_menu_qt_lin.setBackgroundDrawable(null);

   }
  });
  jinrilg_menu_shjj_lin.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    MENU_INDEX = 4;

    processdialog1 = new ProgressDialog(JinRilgActivity.this);
    processdialog1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    processdialog1.setMessage("图片资源加载当中...");
    processdialog1.setIndeterminate(false);
    processdialog1.setCancelable(false);
    processdialog1.setButton("取消",
      new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface arg0, int arg1) {
        processdialog1.dismiss();
        // JinRilgActivity.this.finish();
       }
      });
    processdialog1.show();

    final JinRilg1 lg4 = new JinRilg1("6");
    new Thread() {
     @Override
     public void run() {
      handler.postDelayed(lg4, 1000);
     }
    }.start();

    jinrilg_menu_shjj_lin
      .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
    jinrilg_menu_msfl_lin.setBackgroundDrawable(null);
    jinrilg_menu_ssgw_lin.setBackgroundDrawable(null);
    jinrilg_menu_fzxb_lin.setBackgroundDrawable(null);
    jinrilg_menu_qt_lin.setBackgroundDrawable(null);

   }
  });
  jinrilg_menu_qt_lin.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    MENU_INDEX = 5;

    processdialog1 = new ProgressDialog(JinRilgActivity.this);
    processdialog1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    processdialog1.setMessage("图片资源加载当中...");
    processdialog1.setIndeterminate(false);
    processdialog1.setCancelable(false);
    processdialog1.setButton("取消",
      new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface arg0, int arg1) {
        processdialog1.dismiss();
        // JinRilgActivity.this.finish();
       }
      });
    processdialog1.show();

    final JinRilg1 lg5 = new JinRilg1("0");
    new Thread() {
     @Override
     public void run() {
      handler.postDelayed(lg5, 1000);
     }
    }.start();

    jinrilg_menu_qt_lin
      .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
    jinrilg_menu_msfl_lin.setBackgroundDrawable(null);
    jinrilg_menu_ssgw_lin.setBackgroundDrawable(null);
    jinrilg_menu_fzxb_lin.setBackgroundDrawable(null);
    jinrilg_menu_shjj_lin.setBackgroundDrawable(null);

   }
  });
  // 点击整个Window触发的事件
  popupWindow.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
   }
  });
  // 默认分类菜单没有选中的,点击第一次后,会自动记录点击位,在第二次再点击的时候,会显示上次点的。
  switch (MENU_INDEX) {
  case 1:
   jinrilg_menu_msfl_lin
     .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
   break;
  case 2:
   jinrilg_menu_ssgw_lin
     .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
   break;
  case 3:
   jinrilg_menu_fzxb_lin
     .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
   break;
  case 4:
   // 设置点击背景
   jinrilg_menu_shjj_lin
     .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
   break;
  case 5:
   jinrilg_menu_qt_lin
     .setBackgroundResource(R.drawable.jinrilg_fenlei_menu);
   break;
  default:
   break;
  }

  // 设置背景透明度( //设置背景颜色)
  popupWindow.setBackgroundColor(Color.BLACK);
  popupWindow.getBackground().setAlpha(90);

  popupWindow.invalidate(); // 刷新一下
  mScreenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 获取屏幕宽
  mScreenHeight = getWindowManager().getDefaultDisplay().getHeight(); // 获取屏幕高
  // 设置弹出的window的宽和高,以及显示的布局文件
  mPopupWindow = new PopupWindow(popupWindow, mScreenWidth, mScreenHeight);
 }

 // 编写相关线程(读取相关数据)
 public class JinRilg implements Runnable {
  // 设置请求时间参数
  final int REQUEST_TIMEOUT = 10 * 1000;// 设置请求超时10秒钟
  final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟

  @Override
  public void run() {
   try {
    // 请求路径(servlet)
    String httpurl = Settings.path + "/allGoods";
    // post请求
    HttpPost post = new HttpPost(httpurl);
    // 设置超时时间
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,
      REQUEST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
    // 设置请求实体
    HttpClient httpclient = new DefaultHttpClient(httpParams);
    // 设置响应实体
    HttpResponse httpresponse = httpclient.execute(post);
    // 判断状态码(200)
    if (httpresponse.getStatusLine().getStatusCode() == 200) {
     // 查询结果(json格式数据)
     String json = EntityUtils
       .toString(httpresponse.getEntity());
     Message message = new Message();
     Bundle bundle = new Bundle();
     bundle.putString("json", json);
     message.setData(bundle);
     message.what = 0;
     handler.sendMessage(message);
    } else {
     // 信息提示
     Toast.makeText(JinRilgActivity.this,
       "温馨提示:网络连接超时,请检查网络...", Toast.LENGTH_LONG).show();
     // 关闭进度对话框
     processdialog.cancel();

    }

   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }

 }

 // 今日乐购(商品信息的分类查询)
 // 编写相关线程(读取相关数据)(分类查询)
 public class JinRilg1 implements Runnable {
  private String type;

  public JinRilg1(String type) {
   super();
   this.type = type;
  }

  // 设置请求时间参数
  final int REQUEST_TIMEOUT = 10 * 1000;// 设置请求超时10秒钟
  final int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟

  @Override
  public void run() {
   try {
    // 请求路径(servlet)
    String httpurl = Settings.path + "/allGoods";
    // post请求
    HttpPost post = new HttpPost(httpurl);
    // 设置超时时间
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,
      REQUEST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
    // 添加相关参数
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("type", type));
    // post请求设置请求的参数
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    // 设置请求实体
    HttpClient httpclient = new DefaultHttpClient(httpParams);
    // 设置响应实体
    HttpResponse httpresponse = httpclient.execute(post);
    // 判断状态码(200)
    if (httpresponse.getStatusLine().getStatusCode() == 200) {
     // 查询结果(json格式数据)
     String json = EntityUtils
       .toString(httpresponse.getEntity());
     Message message = new Message();
     Bundle bundle = new Bundle();
     bundle.putString("json", json);
     message.setData(bundle);
     message.what = 1;
     handler.sendMessage(message);
    } else {
     // 信息提示
     Toast.makeText(JinRilgActivity.this,
       "温馨提示:网络连接超时,请检查网络...", Toast.LENGTH_LONG).show();

    }

   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }

 }

 /**
  * 用于请求查询数据。这里是静态的, 必须通过线程访问后台服务进行查询, 并在消息队列中进行处理显示以及加载数据到ListView
  */
 public void findJinRiLeGou1(String json) {
  try {
   // 相关数据清除
   lists1.clear();
   JSONArray jsonarray = new JSONArray(json);
   if (jsonarray.length() > 0) {
    // 相关信息的循环遍历
    for (int i = 0; i < jsonarray.length(); i++) {
     JSONObject object = jsonarray.getJSONObject(i);
     // 商品编号
     String daogou_bh = object.getString("goodId");
     // 商品标题
     String daogou_spbt = object.getString("goodName");
     // 商品原价格
     double daogou_spjg = object.getDouble("price");
     // 商品折扣
     double daogou_spzk = object.getDouble("discount");
     // 商品购买人数
     int daogou_gmrs = object.getInt("persons");
     // 商品优惠时间
     String daogou_yhsj = object.getString("endtime");
     // 商品图片路径
     String daogou_tpsp = object.getString("imgpath");
     // 商品现在价格
     double daogou_xzjg = object.getDouble("newprice");
     // 商品介绍
     String daogou_spjs = object.getString("intro");
     // 商家信息(待检查)
     // String daogou_sjxx=object.getString("");

     // 相关信息的存储工作
     JinriLg jinrilg = new JinriLg();
     // 商品购买人数
     jinrilg.setNumber(daogou_gmrs);
     // 商品名称
     jinrilg.setCommodity(daogou_spbt);
     // 商品销售时间
     jinrilg.setTime(daogou_yhsj);
     // 商品原价格
     jinrilg.setProduct_list(daogou_spjg);
     // 商品折扣
     jinrilg.setMerchandise_discounts(daogou_spzk);
     // 商品现价
     jinrilg.setNow_price(daogou_xzjg);
     // 商品图片
     jinrilg.setImageurl(Settings.service_path
       + Settings.file_path + daogou_tpsp);
     // 商品介绍
     jinrilg.setIntroduction(daogou_spjs);
     // 添加商品编号
     jinrilg.setBianhao(daogou_bh);
     // 相关数据信息添加
     lists1.add(jinrilg);
    }
   } else {
    // 相关提示
    Toast.makeText(JinRilgActivity.this, "温馨提示:无商品信息...",
      Toast.LENGTH_LONG).show();
    // 关闭进度对话框
    processdialog1.cancel();

    if (mPopupWindow != null) {
     mPopupWindow.dismiss();
     mPopupWindow = null;
    }
    return;
   }
   // 相关组件的初始化工作
   MyAdapter adapter = new MyAdapter(lists1, imageloader,
     JinRilgActivity.this);
   listview.setAdapter(adapter);
   // 关闭进度对话框
   processdialog1.cancel();
   if (mPopupWindow != null) {
    mPopupWindow.dismiss();
    mPopupWindow = null;
   }

  } catch (JSONException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

记住:红线的相关代码

 

标签:Android
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号