安卓开发中各种转化关系和开发用的小工具类

package com.android.wandong.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.android.wandong.R;
import com.android.wandong.base.App;
import com.android.wandong.base.BaseResponseBean;
import com.android.wandong.base.UserInfo;
import com.android.wandong.ui.fragment.login.LoginFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;
import com.zhan.framework.common.setting.SettingUtility;
import com.zhan.framework.network.HttpRequestParams;
import com.zhan.framework.utils.Consts;
import com.zhan.framework.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.json.JSONTokener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static java.util.Calendar.DAY_OF_MONTH;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.YEAR;

/**
 * 作者:王天岳 on 2016/3/7 21:55
 * 邮箱:4909367@qq.com
 * //
 * //         .............................................
 * //                  美女坐镇                  BUG辟易
 * //         .............................................
 * //
 * //                       .::::.
 * //                     .::::::::.
 * //                    :::::::::::
 * //                 ..:::::::::::'
 * //              '::::::::::::'
 * //                .::::::::::
 * //           '::::::::::::::..
 * //                ..::::::::::::.
 * //              ``::::::::::::::::
 * //               ::::``:::::::::'        .:::.
 * //              ::::'   ':::::'       .::::::::.
 * //            .::::'      ::::     .:::::::'::::.
 * //           .:::'       :::::  .:::::::::' ':::::.
 * //          .::'        :::::.:::::::::'      ':::::.
 * //         .::'         ::::::::::::::'         ``::::.
 * //     ...:::           ::::::::::::'              ``::.
 * //    ```` ':.          ':::::::::'                  ::::..
 * //                       '.:::::'                    ':'````..
 * //
 */
public class Tools {

    public static String md5(String string) {
        byte[] hash = null;
        try {
            hash = string.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh,UTF-8 should be supported?", e);
        }
        return computeMD5(hash);
    }

    public static String computeMD5(byte[] input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input, 0, input.length);
            byte[] md5bytes = md.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < md5bytes.length; i++) {
                String hex = Integer.toHexString(0xff & md5bytes[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    /***
     * 解析服务器时间,服务器是GMT+08时区
     *
     * @param serverTimeStr
     * @return 返回 时间戳
     */
    /*public static long parseServerTime(String serverTimeStr) {
        if (TextUtils.isEmpty(serverTimeStr)) {
            return 0;
        }
        final String FORMAT = "yyyy-MM-dd HH:mm:ss";
        Date date = DateUtil.parseDate(serverTimeStr, FORMAT, TimeZone.getTimeZone("GMT+08"));
        if (date == null) {
            return 0;
        }
        return date.getTime();
    }*/

    /***
     * 时间戳转换
     */
    public static String parseTimeToMinutes(Long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
        String strTime = format.format(date);
        return strTime;
    }

    /***
     * 时间戳转换
     */
    public static String parseTime(Long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strTime = format.format(date);
        return strTime;
    }

    public static String parseTimeToDateStr(Long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String strTime = format.format(date);
        return strTime;
    }

    public static long parseDateStrToLong(String dataStr) {
        if (TextUtils.isEmpty(dataStr)) {
            return 0;
        }
        String date = dataStr.replace("/Date(", "");
        date = date.replace(")/", "");
        try {
            return Long.valueOf(date);
        } catch (Exception ex) {
            return 0;
        }
    }

    public static String parseTimeToChinaYearMinutes(Long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.ENGLISH);
        String strTime = format.format(date);
        return strTime;
    }

    public static String parseTimeToChinaYearMinutes(String dateStr) {
        Long time = parseDateStrToLong(dateStr);
        return parseTimeToChinaYearMinutes(time);
    }

    public static String parseTimeToChinaMonthMinutes(Long time) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日 HH:mm", Locale.ENGLISH);
        String strTime = format.format(date);
        return strTime;
    }

    public static String parseTimeToChinaMonthMinutes(String dateStr) {
        Long time = parseDateStrToLong(dateStr);
        return parseTimeToChinaMonthMinutes(time);
    }


    /***
     * 将时间戳转换为日期或时间字符串,当前显示时间其他显示日期
     *
     * @param time
     * @return
     */
    public static String parseToTimeOrDateStr(Long time) {
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = formatDate.format(time);

        SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
        String strTime = formatTime.format(time);

        String strDateToday = formatDate.format(System.currentTimeMillis());
        if (strDateToday.equals(strDate)) {
            return strTime;
        } else {
            return strDate;
        }
    }

    /***
     * 将时间戳装换为服务器时间字符串
     * 服务器是GMT+08时区
     *
     * @param time
     * @return
     */
    /*public static String formatToServerTimeStr(long time) {
        if (time > 0) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));
            Date date = new Date(time);
            return dateFormat.format(date);
        } else {
            return null;
        }
    }*/


    /***
     * 装换Json
     *
     * @param json
     * @param beanClass
     * @return 如果转换出错 返回
     */
    public static <T extends BaseResponseBean> T parseJson(String json, Class<T> beanClass) {
        T bean = null;
        try {
            bean = JSON.parseObject(json, beanClass);
        } catch (JSONException ex) {
            Log.e("Utils", "fromJson error : " + ex.getMessage());
        }
        return bean;
    }

    /**
     * 将Json String 转换为JsonObject 如果Json格式错误或Code!=0 返回null
     *
     * @param json
     * @param beanClass
     * @param <T>
     * @return 转换正确且Code==0返回 beanClass,否则返回null,并Toast 错误信息
     */
    public static <T extends BaseResponseBean> T parseJsonTostError(String json, Class<T> beanClass) {
        T bean = parseJson(json, beanClass);
        if (bean == null) {
            ToastUtils.toast(R.string.json_syntax_error);
        } else if (bean.isSuccess()) {
            return bean;
        } else {
            // 取消数据为空,或异常情况的消息提示
            ToastUtils.toast(bean.getMsg());
        }
        return null;
    }


    public static String verifyResponseResult(String jsonStr) {
        String errorMsg = null;
        BaseResponseBean bean = parseJson(jsonStr, BaseResponseBean.class);
        if (bean == null) {
            errorMsg = App.getInstance().getString(R.string.json_syntax_error);
        } else if (bean.isSuccess()) {
            errorMsg = null;
        } else {
            // 取消数据为空,或异常情况的消息提示
            errorMsg = bean.getMsg();
        }
        return errorMsg;
    }

    public static String verifyResponseResult(BaseResponseBean bean) {
        String errorMsg = null;
        if (bean == null) {
            errorMsg = App.getInstance().getString(R.string.json_syntax_error);
        } else if (bean.isSuccess()) {
            errorMsg = null;
        } else {
            // 取消数据为空,或异常情况的消息提示
            errorMsg = bean.getMsg();
        }
        return errorMsg;
    }

    public static boolean sameDate(Calendar cal, Calendar selectedDate) {
        return cal.get(MONTH) == selectedDate.get(MONTH)
                && cal.get(YEAR) == selectedDate.get(YEAR)
                && cal.get(DAY_OF_MONTH) == selectedDate.get(DAY_OF_MONTH);
    }

    public static boolean betweenDates(Calendar cal, Calendar minCal, Calendar maxCal) {
        final Date date = cal.getTime();
        return betweenDates(date, minCal, maxCal);
    }

    public static boolean betweenDates(Date date, Calendar minCal, Calendar maxCal) {
        final Date min = minCal.getTime();
        return (date.equals(min) || date.after(min)) // >= minCal
                && date.before(maxCal.getTime()); // && < maxCal
    }

    public static void hideSoftInputFromWindow(View view) {
        InputMethodManager imm = (InputMethodManager) App.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    //显示虚拟键盘
    public static void showSoftInputFromWindow(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 下载并安装app
     *
     * @param url
     */
    public static void installApp(String url) {
        final DownloadManager systemService = (DownloadManager) App.getInstance().getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "upgrade.apk");
        systemService.enqueue(request);
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        final BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
                myDownloadQuery.setFilterById(reference);

                Cursor myDownload = systemService.query(myDownloadQuery);
                if (myDownload.moveToFirst()) {
                    int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

                    String fileUri = myDownload.getString(fileUriIdx);

                    Intent ViewInstallIntent = new Intent(Intent.ACTION_VIEW);
                    ViewInstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    ViewInstallIntent.setDataAndType(Uri.parse(fileUri), "application/vnd.android.package-archive");
                    context.startActivity(ViewInstallIntent);
                }
                myDownload.close();

                App.getInstance().unregisterReceiver(this);
            }
        };
        App.getInstance().registerReceiver(receiver, filter);
    }


    public static int getScreenWidth(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static Dialog createDialog(Activity context, int dialogLayoutRes) {
        final Dialog dialog = new Dialog(context, com.zhan.framework.R.style.Dialog);
        dialog.setContentView(dialogLayoutRes);
        /*Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();

        int screenW = getScreenWidth(context);
        lp.width = (int) (0.6 * screenW);*/
        return dialog;
    }

    public static Dialog showConfirmDialog(Activity activity, String title, String summary, View.OnClickListener onConfirmClickListener, Object tag) {

        final Dialog confirmDialog = Tools.createDialog(activity, R.layout.dialog_cancel_or_confirm);

        TextView titleView = (TextView) confirmDialog.findViewById(R.id.title);
        titleView.setText(title);
        TextView summaryView = (TextView) confirmDialog.findViewById(R.id.summary);
        summaryView.setText(summary);

        TextView cancelBtn = (TextView) confirmDialog.findViewById(R.id.cancel);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmDialog.dismiss();
            }
        });

        TextView confirmBtn = (TextView) confirmDialog.findViewById(R.id.confirm);
        confirmBtn.setTag(tag);
        confirmBtn.setOnClickListener(onConfirmClickListener);

        confirmDialog.show();

        return confirmDialog;
    }

    public static Dialog showDialogFromBottom(Activity activity, int dialogLayout, boolean showSoftInput) {
        Dialog dialog = new Dialog(activity, com.zhan.framework.R.style.Dialog);
        dialog.setContentView(dialogLayout);
        Window window = dialog.getWindow();
        if (showSoftInput) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = Tools.getScreenWidth(activity);
        window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.pop_menu_animation);  //添加动画
        dialog.show();

        return dialog;
    }

    public static boolean checkMobilePhoneNumber(String phoneNumber) {
        String telRegex = "[1]\\d{10}";
        if (TextUtils.isEmpty(phoneNumber)) return false;
        else return phoneNumber.matches(telRegex);
    }

    public static String parseTimeLeftStr(long between) {
        int day = (int) (between / (24 * 60 * 60 * 1000));
        int hour = (int) (between / (60 * 60 * 1000) - day * 24);
        int min = (int) ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
        int second = (int) (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

        return String.format("%02d天 %02d小时 %02d分 %02d秒", day, hour, min, second);
    }

    private static DisplayImageOptions sDefAvatarDisplayImageOptions;

    /**
     * 头像选项
     *
     * @return
     */
    public static DisplayImageOptions buildDisplayImageOptionsForAvatar() {
        if (sDefAvatarDisplayImageOptions == null) {
            sDefAvatarDisplayImageOptions = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.bg_head_portrait)
                    .showImageForEmptyUri(R.drawable.bg_head_portrait)
                    .showImageOnFail(R.drawable.bg_head_portrait)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .considerExifParams(true)
                    .build();
        }
        return sDefAvatarDisplayImageOptions;
    }

    private static DisplayImageOptions sDefDisplayImageOptions;

    public static DisplayImageOptions buildDefDisplayImgOptions() {
        if (sDefDisplayImageOptions == null) {
            sDefDisplayImageOptions = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.def_pic)
                    .showImageForEmptyUri(R.drawable.def_pic)
                    .showImageOnFail(R.drawable.def_pic)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .considerExifParams(true)
                    .build();
        }
        return sDefDisplayImageOptions;
    }


    public static DisplayImageOptions buildDisplayImgOptions(int defPic) {
        DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
                .showImageOnLoading(defPic)
                .showImageForEmptyUri(defPic)
                .showImageOnFail(defPic)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .build();
        return displayImageOptions;
    }

    public static void removeImgFromCache(String imgUrl) {
        MemoryCacheUtils.removeFromCache(imgUrl, ImageLoader.getInstance().getMemoryCache());
        DiskCacheUtils.removeFromCache(imgUrl, ImageLoader.getInstance().getDiskCache());
    }

    public static void clearImgCahce() {
        ImageLoader.getInstance().clearDiskCache();
        ImageLoader.getInstance().clearMemoryCache();
    }

    private static long lastClickTime;

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void setTextView(TextView textView, String text) {
        if (textView == null) {
            return;
        }
        if (TextUtils.isEmpty(text)) {
            textView.setText("");
        } else {
            textView.setText(text);
        }
    }

    /***
     * 检测是否登录,如果没有登录就启动登录页面
     *
     * @param activity
     * @return
     */
    public static boolean checkIsLogin(Activity activity) {
        if (UserInfo.getCurrentUser() == null || !UserInfo.getCurrentUser().isLogin()) {
            LoginFragment.launch(activity);
            return false;
        }
        return true;
    }

    public static HttpRequestParams createHttpRequestParams() {
        HttpRequestParams requestParams = new HttpRequestParams();
        if (UserInfo.getCurrentUser() != null && UserInfo.getCurrentUser().isLogin()) {
            requestParams.put("UserId", UserInfo.getCurrentUser().getUserId());
            requestParams.put("UserName", UserInfo.getCurrentUser().getLoginAccount());
            requestParams.put("PassWord", UserInfo.getCurrentUser().getPassword());
        }
        return requestParams;
    }

    public static String parseDistance(double distance) {
        DecimalFormat df = new DecimalFormat();
        df.applyPattern("###.##米");

        DecimalFormat df2 = new DecimalFormat();
        df2.applyPattern("###,###.##里");
        if (distance < 1000) {
            return df.format(distance);
        } else {
            return df2.format(distance * 2 / 1000);
        }
    }

    /**
     * 万、亿处理,最多保留两位小数,超过超过部分直接舍去,不四舍五入
     *
     * @param money
     * @return
     */
    public static String getMoneyFromDouble(double money) {
        if (money == 0) {
            return "0";
        }
        DecimalFormat df = new DecimalFormat("#.00");
        if (money < 10000) {
            //不到万,保留两位小数
            return getDoubleFromStr(df.format(money)) + "元";
        } else if (money < 100000000) {
            //不到亿
//            long round = Math.round(money / 10000);
//            return round + "万";
            money /= 10000;
            return getDoubleFromStr(df.format(money)) + "万";
        } else {
            //亿以上
            money /= 100000000;
//            long round = Math.round(money / 100000000);
//            return round + "亿";
            return getDoubleFromStr(df.format(money)) + "亿";
        }
//        return df.format(money);
    }

    public static String getMoneyFromString(String str) {
        if (TextUtils.isEmpty(str)) {
            return "0";
        }
        double v = Double.parseDouble(str);
        return String.valueOf((int) v);
    }

    /**
     * base64算法将文件转成字符串
     *
     * @return
     */
    public static String file2String(File file) {
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fs.read(b)) != -1) {
                out.write(b, 0, len);
            }
            byte[] bytes = out.toByteArray();
            byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
            return new String(encode);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fs != null) try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 四舍五入,保留一位小数
     *
     * @return
     */
    public static String get2Decimal(double d) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(d);
    }


    /**
     * @param d 元
     * @return 保留一位小数的字符串 万元
     */
    public static String double2Str(double d) {
        d /= 10000;
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(d);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 设置批准信息
     *
     * @param context
     * @param result  其内容为空、通过、驳回三者之一
     * @param name
     * @param iv
     */
    public static void setApprovalData(Context context, String result, TextView name, ImageView iv, ImageView head, String headUrl) {
        ImageLoader.getInstance().displayImage(SettingUtility.getSetting(Consts.BASE_URL).getValue() + headUrl, head, Tools.buildDisplayImageOptionsForAvatar());
        if (TextUtils.isEmpty(result)) {
            name.setTextColor(context.getResources().getColor(R.color.text999999));
            iv.setImageResource(R.drawable.ic_approval_wait);
        } else {
            name.setTextColor(context.getResources().getColor(R.color.text333333));
            if (Constant.PASS.equals(result)) {
                iv.setImageResource(R.drawable.ic_approval_pass);
            } else {
                iv.setImageResource(R.drawable.ic_approval_reject);
            }
        }
    }


    /**
     * @param str 可转成double类型的字符串
     * @return 最多保留两位小数的double类型字符串(若为小数,则小数末尾的0会被去除,如1.0-->1, 1.10-->1.1)
     */
    public static String getDoubleFromStr(String str) {
        if (TextUtils.isEmpty(str)) {
            return "0";
        }
        int i = str.indexOf(".");
        if (i == -1) {
            //整数
            return str;
        } else if (i == str.length() - 1) {
            //整数,最后一位是小数点,但没有小数部分
            return str.substring(0, str.length() - 1);
        }

        for (int j = 0; j < 2; j++) {
            if (i + 1 <= str.length()) {
                i++;
            } else {
                break;
            }
        }
        if (i + 1 <= str.length()) {
            str = str.substring(0, i + 1);
        }
        try {
            double v = Double.parseDouble(str);
            int w = (int) v;
            if (w == v) {
                return String.valueOf(w);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        while (str.endsWith("0")) {
            str = str.substring(0, str.length() - 1);
        }
        if (str.indexOf(".") == str.length() - 1) {
            //整数,最后一位是小数点,但没有小数部分
            return str.substring(0, str.length() - 1);
        }
        return str;
    }

    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

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

        return pi;
    }

    public static void setListViewHeightBasedOnChildren(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);
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值