Android常用工具

来源:互联网 发布:单页用什么软件有哪些 编辑:程序博客网 时间:2024/05/26 12:57

显示图片: 

// 加载网络图片,设定默认图片

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.default_loading_img_100x100)
                .showImageForEmptyUri(R.drawable.default_loading_img_100x100)
                .showImageOnFail(R.drawable.default_loading_img_100x100)
                .build();


        ImageLoader.getInstance().displayImage(list.get(0).getImgName(),

                fruitImg, options);

// 显示头像
        Constants.loadImage(R.drawable.news_head, WorkApplication.getInstance().getFullLogoUrl(), logo);


输入中文转码:

params.put("signInAddress", URLEncoder.encode(locationString, "utf-8"));


String转date形势的String:

Date date = new Date(time);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String strDate=df.format(date);


调接口:

ProgressDialogUtil.showMsgDialogSingle(this);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("shopId", shopId);
        map.put("pNo", pageCouple);
        map.put("isFristLoad", isFristLoad);
        map.put("isLoadMore", isLoadMore);
        MainService.newTask(new Task(TaskType.STORE_COUPON, map));


// 修改其他layout:

//初始化列表
            View viewParent = LayoutInflater.from(this).inflate(R.layout.order_goods, null);
            ImageView commodityImage = (ImageView) viewParent.findViewById(R.id.commodity_image);



/**
     * 设置Listview的高度
     */ 

    public void setListViewHeight(ListView listView) {  
        ListAdapter listAdapter = listView.getAdapter();   
        if(listAdapter == null) {  
            return;  
        }  
        int totalHeight = 0;  
        for (int i = 0; i < listAdapter.getCount(); i++) {  
            View listItem = listAdapter.getView(i, null, listView);  
            listItem.measure(0, 0);  
            totalHeight += listItem.getMeasuredHeight();  
        }  
        ViewGroup.LayoutParams params = listView.getLayoutParams();  
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));  
        listView.setLayoutParams(params); 
    }


解析为list集合(先jasonArray):

public static ConnResult<List<MyHouseInfo>> jsonParseHouseList(String response) {


       ConnResult<List<MyHouseInfo>> resultInfo = null;
       if (StringUtil.isNull(response)) {
           return null;
       }
       JSONObject obj = null;
       try {
           resultInfo = new ConnResult<List<MyHouseInfo>>();
           obj = new JSONObject(response);
           int resultCode = obj.getInt(ConnResult.RESULT_CODE);
           resultInfo.setResultCode(resultCode);
           resultInfo.setMessage(obj.getString(ConnResult.RESULT_STRING_FLAG));
           
           if (resultCode == NetConstants.RESULTCODE_SUCCESS) {
               JSONArray result = obj.getJSONArray(ConnResult.RETURN_INFO_FLAG);
               
                   List<MyHouseInfo> list = new ArrayList<MyHouseInfo>();
                   for (int i = 0; i < result.length(); i++) {
                       JSONObject object = null;
                       try {
                           object = result.getJSONObject(i);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                       MyHouseInfo myHouseInfo = new MyHouseInfo();
                       myHouseInfo.setCellName(valueIsEqualsNull(object, "cellName") ? "" : object.getString("cellName"));
                       myHouseInfo.setHouseId(valueIsEqualsNull(object, "id") ? "" : object.getString("id"));
                       list.add(myHouseInfo);
                   }
               resultInfo.setResultObject(list);
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return resultInfo;
   }


解析为list集合(先jasonObj):

 /**获取店铺列表*/
    public static ConnResult<List<StoreListInfo>> jsonParseMallGetShopList(String response) {


        ConnResult<List<StoreListInfo>> resultInfo = null;
        if (StringUtil.isNull(response)) {
            return null;
        }
        JSONObject obj = null;
        try {
            resultInfo = new ConnResult<List<StoreListInfo>>();
            obj = new JSONObject(response);
            int resultCode = obj.getInt(ConnResult.RESULT_CODE);
            resultInfo.setResultCode(resultCode);
            resultInfo.setMessage(obj.getString(ConnResult.RESULT_STRING_FLAG));
            
            if (resultCode == NetConstants.RESULTCODE_SUCCESS) {
                
                JSONObject result = obj.getJSONObject(ConnResult.RETURN_INFO_FLAG);
                List<StoreListInfo> list = new ArrayList<StoreListInfo>();
                resultInfo.setTotalPage(valueIsEqualsNull(result, "pages") ? 0 : result.getInt("pages"));
                if (result.has("list")) {
                    JSONArray array = result.getJSONArray("list");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        StoreListInfo info = new StoreListInfo();
                        info.setName(valueIsEqualsNull(object, "name") ? "" : object.getString("name"));
                        info.setDescrip(valueIsEqualsNull(object, "descrip") ? "" : object.getString("descrip"));
                        info.setBeginTime(valueIsEqualsNull(object, "beginTime")? "" : object.getString("beginTime"));
                        info.setEndTime(valueIsEqualsNull(object,"endTime")? "" :object.getString("endTime"));
                        info.setLogo(valueIsEqualsNull(object,"logo")? "" :object.getString("logo"));
                        
                        list.add(info);
                    }
                }
                resultInfo.setResultObject(list);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultInfo;
    }


refresh处理数据:

case TaskType.GET_PLATFORM_COUPON:{
            if (msg.obj == null) {
                if (!Constants.NetworkStatus) {
                    Constants.commonToast(getActivity(), R.string.network_error);
                }else{
                    Constants.commonToast(getActivity(), "连接超时");
                }
                break;
            }
            ConnResult<List<CouponInfo>> result = (ConnResult<List<CouponInfo>>) msg.obj;
            if (result.getResultCode() == NetConstants.RESULTCODE_SUCCESS) {
                if (couponInfoList == null) {
                    couponInfoList = new ArrayList<CouponInfo>();
                    couponInfoList.addAll(result.getResultObject());
                }else {
                    couponInfoList.clear();
                    couponInfoList.addAll(result.getResultObject());
                }
                // 显示数据
                initPlatformCoupon();
            }else {
                Constants.commonToast(getActivity(), result.getMessage());
            }
            break;
        }


onClick跳转页面:

public void onClick(View v) {
   
   Bundle bundle = new Bundle();
   
switch (v.getId()) {
case R.id.goods_search:
openActivity(MallSearchActivity.class);
break;
case R.id.btn_fruit:
       bundle.putString("shopCategoryId", fruitCategoryId);
       openActivity(StoreListActivity.class, bundle);
            break;


adapter里点击跳转到activity:

viewHold.wholeList.setTag(storeListInfo.getShopId());
        viewHold.wholeList.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // 跳转到详情页
                Bundle bundle = new Bundle();
                bundle.putString("shopId", v.getTag().toString());
                
                Intent intent = new Intent(context, StoreDetailsActivity.class);
                if (bundle != null) {
                    intent.putExtras(bundle);
                }
                context.startActivity(intent);
            }
        });



// 监听回车

onCreate{
        keywordEdit.setOnKeyListener(onKey);
    }


    OnKeyListener onKey = new OnKeyListener() {


        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {




            if (keyCode == KeyEvent.KEYCODE_ENTER) {


                InputMethodManager imm = (InputMethodManager) v.getContext()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);


                if (imm.isActive()) {


                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),
                            0);

                }
                searchText = keywordEdit.getText().toString().trim();
                getShopList(true, false);
                return true;
            }
            return false;
        }
    };



手机输入键盘回车自动搜索:

 //把虚拟键盘的回车改成搜索          good_search.setImeOptions(EditorInfo.IME_ACTION_SEND);         // 监听键盘上的搜索        good_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {              @Override              public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {                  if (actionId==EditorInfo.IME_ACTION_SEND)                   {                           search();                                   }                 return false;              }          }); 

Fragment收起输入法弹框:

Activity改成this

/** * 收起软键盘并设置提示文字 */protected void hideSoftInput() {          View v = getActivity().getCurrentFocus();          if (v != null && v.getWindowToken() != null) {              InputMethodManager manager = (InputMethodManager) getContext()                      .getSystemService(Context.INPUT_METHOD_SERVICE);              boolean isOpen = manager.isActive();              if (isOpen) {                  imm.hideSoftInputFromWindow(v.getWindowToken(), 0);            }          }      }  



需求:在手机中显示图片,宽度为手机宽度,高度根据宽度自适应缩放。

    

Android-Universal-Image-Loader库中DisplayImageOptions中的函数imageScaleType(ImageScaleType imageScaleType)是用来设置图片的缩放方式,参数如下:

ImageScaleType.EXACTLY :图像将完全按比例缩小的目标大小
ImageScaleType.EXACTLY_STRETCHED:图片会缩放到目标大小完全
ImageScaleType.IN_SAMPLE_INT:图像将被二次采样的整数倍
ImageScaleType.IN_SAMPLE_POWER_OF_2:图片将降低2倍,直到下一减少步骤,使图像更小的目标大小
ImageScaleType.NONE:图片不会调整

设置如下:imageScaleType(ImageScaleType.EXACTLY_STRETCHED)


public static void loadImage(int defaultDrawable, String url, ImageView iv) {if (!url.startsWith("http")) {url = WorkApplication.getInstance().getGlobalImageurl() + url;}        DisplayImageOptions options = new DisplayImageOptions.Builder()            .showImageOnLoading(defaultDrawable)            .showImageForEmptyUri(defaultDrawable)            .showImageOnFail(defaultDrawable)            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // 设置图片按比例缩放            .build();                        ImageLoader.getInstance().displayImage(url, iv, options);    }


ImageView设置如下:

<ImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>  //高度也可以设置为match_parent,都一样



0 0
原创粉丝点击