代码二次封装-xUtils(android)

Posted slgkaifa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代码二次封装-xUtils(android)相关的知识,希望对你有一定的参考价值。

通常我们会引用很多lib
而且会出现lib 与我们的功能仅仅差一点点 这种情况我们最好不要去改动源代码 而是进行二次封装

举例我使用 xUtils的二次封装 此处说明我是搞ios的 这个是android 今天mac 机子没网 蛋疼

使用到pulltorefresh 和 xUtils

  1. 网络封装
    因为此处是没有文件处理所以我把參数转换里面file给去掉了 假设须要自行加上就可以

public class ApiHttpUtil {
    final public static String base_url_api = Constants.base_url_api;
    private String api_url;
    HttpApiCallBack callBack;
    Map<String, String> paramsMap;
    CacheEntity cacheEntity;

    Long timeOut = 0L;

    public ApiHttpUtil() {
    }

    public ApiHttpUtil(HttpApiCallBack callBack) {
        this.callBack = callBack;
        this.cacheEntity = new CacheEntity();
    }

    public ApiHttpUtil(String url, HttpApiCallBack callBack) {
        this.api_url = url;
        this.callBack = callBack;
        this.cacheEntity = new CacheEntity();
    }

    public String getApiUrl() {
        if (StringUtils.isEmpty(api_url)) {
            return base_url_api + "?";
        }
        if (api_url.startsWith("http")) {
            return api_url;
        }
        return base_url_api + "/" + api_url;
    }

    public String strValue(Object obj) {
        if (obj instanceof String) {
            return (String) obj;
        } else if (obj instanceof Integer) {
            return Integer.toString((Integer) obj);
        } else if (obj instanceof Double) {
            return Double.toString((Double) obj);
        } else {
            // TODO 其它 object 类转换 http string
        }
        return String.valueOf(obj);
    }

    public void getObjs(Object... objs) {
        Map<String, Object> map = getMap(objs);
        get(map);
    }

    public void postObjs(Object... objs) {
        Map<String, Object> map = getMap(objs);
        post(map);
    }

    /*
     * key --- String Integer Double value -- +File
     */
    public Map<String, Object> getMap(Object[] objs) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (objs.length % 2 == 0) {
            for (int i = 0; i < objs.length; i += 2) {
                try {
                    String key = (String) strValue(objs[i]);
                    Object value = null;
                    if (objs.length > i + 1) {
                        Object objs2 = objs[i + 1];
                        value = strValue(objs2);
                    }
                    if (value instanceof String) {
                        if (!StringUtils.isEmpty((String) value)
                                && !StringUtils.isEmpty(key)) {
                            map.put(key, value);
                        }
                    } else if (value instanceof File) {
                        map.put(key, value);
                    }
                } catch (Exception e) {
                }
            }
        }
        return map;
    }

    public void get() {
        get(null);
    }

    public void post() {
        post(null);
    }

    public ApiHttpUtil setTimeOut(int second) {
        this.timeOut = second * 1000L;
        return this;
    }

    public void post(Map<String, Object> map) {
        RequestParams params = new RequestParams();
        if (map != null) {
            for (Entry<String, Object> entry : map.entrySet()) {
                if (entry.getValue() instanceof String) {
                    params.addBodyParameter(entry.getKey(),
                            (String) entry.getValue());
                } else {
                    params.addBodyParameter(entry.getKey(),
                            strValue(entry.getValue()));
                }
            }
        }

        if (timeOut <= 0 && !useCache(map)) {
            send(HttpRequest.HttpMethod.POST, params);
        }
    }

    public void get(Map<String, Object> map) {

        RequestParams params = new RequestParams();
        if (map != null) {
            for (Entry<String, Object> entry : map.entrySet()) {
                if (entry.getValue() instanceof String) {
                    params.addQueryStringParameter(entry.getKey(),
                            (String) entry.getValue());
                } else {
                    params.addQueryStringParameter(entry.getKey(),
                            strValue(entry.getValue()));
                }
            }
        }
        if (timeOut <= 0 && !useCache(map)) {
            send(HttpRequest.HttpMethod.GET, params);
        }
    }

    public boolean useCache(Map<String, Object> map) {
        this.cacheEntity.setKey(getApiUrl() + map.toString());
        if (AppContext.mInstance != null) {
            if (!StringUtils.isEmpty(this.cacheEntity.getValue())) {
                if (!AppUtils.isNetworkAvailable(AppContext.mInstance)) {
                    AppUtils.openNetworkSettings(AppContext.mInstance);
                    onSuccess(this.cacheEntity.getCacheValue());
                    return true;
                }
            }
            String result = this.cacheEntity.getValue(timeOut);
            if (!StringUtils.isEmpty(result)) {
                onSuccess(result);
                return true;
            }
        }
        return false;
    }

    public void send(HttpRequest.HttpMethod method, RequestParams params) {
        HttpUtils http = new HttpUtils();
        http.send(method, getApiUrl(), params,
                new RequestCallBack<String>() {
                    @Override
                    public void onStart() {
                        callBack.onStart();
                    }

                    @Override
                    public void onLoading(long total, long current,
                            boolean isUploading) {
                        callBack.onLoading(total, current, isUploading);
                    }

                    @Override
                    public void onCancelled() {
                        callBack.onCancelled();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        ApiHttpUtil.this.onSuccess(responseInfo.result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        callBack.onFailure(error, msg);
                    }
                });
    }

    public boolean handleError(String result) {
        // TODO
        return false;
    }

    public void onSuccess(String result) {
        if (handleError(result)) {
            return;
        }
        if (callBack.onSuccess(result)) {
            cacheEntity.setValue(result);
            return;
        }
        try {
            JSONObject jsonResults = new JSONObject(result);
            callBack.onSuccess(jsonResults);
            cacheEntity.setValue(result);
        } catch (Exception e) {
            callBack.onFailure(e, "JSONObject 解析错误");
            e.printStackTrace();
        }
    }
}

在此贴出部分上面用到的代码


    /*
     * 是否有网
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            Log.i("NetWorkState", "Unavailabel");
            return false;
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        Log.i("NetWorkState", "Availabel");
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /*
     * 打开网络设置界面请求
     */
    public static AlertDialog dialog_networkSettings;
    public static void openNetworkSettings(final Context content) {
        if (dialog_networkSettings == null) {
            dialog_networkSettings = new AlertDialog.Builder(content)
            .setTitle("开启网络服务")
            .setMessage("本软件须要使用网络资源,是否开启网络?")
            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Go to the activity of settings of wireless
                    if (android.os.Build.VERSION.SDK_INT > 13) {
                        content.startActivity(new Intent(
                                android.provider.Settings.ACTION_SETTINGS));
                    } else {
                        content.startActivity(new Intent(
                                android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                    }
                    dialog.cancel();
                }
            })
            .setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).show();
        }else{
            if (!dialog_networkSettings.isShowing()) {
                dialog_networkSettings.show();
            }
        }
    }

意义就在于 对自身的项目需求 做出特殊的代码比方 我碰到的之前一个项目 他后台是thinkphp的所以參数都是:网址+/?a=** 特殊情况做出处理
还有就是比方用户信息 请求得同一时候能够在 自己写的二次封装方法中写 很多其它的针对这一个api的操作 比方 db操作甚至关系的推断等

我封装的一个 BaseAdapter

package yangdc.common.fragment.base;

import org.json.JSONException;
import org.json.JSONObject;
import yangdc.common.api.ApiCallBack;
import yangdc.common.utils.BitmapUtil;
import yangdc.common.utils.StringUtils;
import yangdc.common.utils.ToastUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public abstract class BaseAdapter<EntityT, ViewT> extends ArrayAdapter<EntityT> {
    public Context context;
    int resource;
    public ApiCallBack api;
    public int page = 0;
    ListView listView;
    public BitmapUtil bitmapUtil;
    boolean mHasRequestedMore;// 正在请求
    public boolean isDropDown = true;// 是否是 刷新
    PullToRefreshListView pullToRefreshListView;
    public BaseAdapter(Context context,int resource,PullToRefreshListView pullToRefreshListView) {
        super(context, resource);
        this.pullToRefreshListView = pullToRefreshListView;
        init(context, resource);
    }
    public BaseAdapter(Context context, int resource, ListView listView) {
        super(context, resource);
        this.listView = listView;
        init(context, resource);
    }
    public void init(Context context, int resource){
        this.context = context;
        this.resource = resource;

        initAdapter();
        initbitmapUtil();
        initListViewListener();
    }
    public void initAdapter(){
        if (listView != null) {
            listView.setAdapter(this);
        } else if (pullToRefreshListView != null) {
            pullToRefreshListView.setAdapter(this);
        }
    }
    public void initbitmapUtil() {

        bitmapUtil = new BitmapUtil(context);
        // 控制滑动和高速滑动过程中时候暂停载入图片
        if (listView != null) {
            listView.setOnScrollListener(new PauseOnScrollListener(bitmapUtil,false, true));
            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?

> parent, View view, int position, long id) { OnItemClick(getItem(position-1)); } }); } else if (pullToRefreshListView != null) { pullToRefreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtil,false, true)); pullToRefreshListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { OnItemClick(getItem(position-1)); } }); } } public void OnItemClick(EntityT T){ } public void initListViewListener() { if (pullToRefreshListView != null) { pullToRefreshListView.setMode(Mode.BOTH); pullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { if (refreshView.isHeaderShown()) { isDropDown = true; } else { isDropDown = false; } onLoadMoreItems(); } }); } if (onLoadMoreImmediately()) { onLoadMoreItems(); } } public boolean onLoadMoreImmediately() { return true; } private void complete(){ mHasRequestedMore = false; if (pullToRefreshListView != null) { pullToRefreshListView.onRefreshComplete(); } } public void onLoadMoreItems() { if (mHasRequestedMore) { // 上次请求 还未结束 ToastUtils.show(context, "正在努力载入中..."); } else { final int oldPage = page; if (isDropDown) { page = 1; } else { page++; } if (api == null) { api = new ApiCallBack() { @Override public void onSuccessJson(JSONObject jsonObject) { complete(); if (page == 1) { saveCache(jsonObject); clear();//TODO 推断是否 有新数据 假设是仅仅新增则 加入到头部 其它情况加入到尾部 } BaseAdapter.this.onSuccessJson(jsonObject); } @Override public void onFailure(Exception e, String msg) { complete(); mHasRequestedMore = false; ToastUtils.show(context, msg); page = oldPage; } @Override public void onReady() { if (page==1) { JSONObject result = loadJSONCache(); if (result != null) { onSuccessJson(result); } } } }; } mHasRequestedMore = true; PostObjs(); } } public void onSuccess(String result){ try { onSuccessJson(new JSONObject(result)); } catch (JSONException e) { e.printStackTrace(); } } public abstract void onSuccessJson(JSONObject result); public String URL(){ return null; } public String PostActionMark(){ return api.jsonAction; } public abstract void PostObjs(); public abstract ViewT initView(View convertView); public abstract void updateView(ViewT convertView, EntityT entity); public SharedPreferences getSharedPreferences(){ return context.getSharedPreferences( getClass().getName() , Context.MODE_PRIVATE); } public void saveCache(String cacheStr){ getSharedPreferences().edit().putString(PostActionMark(), cacheStr).commit(); } public void saveCache(JSONObject cacheJson){ saveCache(cacheJson.toString()); } public String loadCache(){ SharedPreferences preferences = getSharedPreferences(); return preferences.getString(PostActionMark(), ""); } public JSONObject loadJSONCache() { String jsonStr = loadCache(); JSONObject jsonObject = null; if (!StringUtils.isEmpty(jsonStr)) { try { jsonObject = new JSONObject(jsonStr); } catch (JSONException e) { e.printStackTrace(); } } return jsonObject; } @SuppressWarnings("unchecked") @Override public View getView(int position, View convertView, ViewGroup parent) { ViewT adapterView = null; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(resource, null); adapterView = initView(convertView); convertView.setTag(adapterView); } else { adapterView = (ViewT) convertView.getTag(); } updateView(adapterView, getItem(position)); return convertView; } }

继承后自须要实现几个方法就可以
技术分享

基本代码意思是
翻页、第一页的缓存、等通用的都让baseclass处理
继承后仅仅须要实现
网络请求时须要的数据、view的初始化以及刷新的内容(会自己主动调用)、以及其它格外处理比方Item点击事件

能用Fragment 的使用Fragment 碎片化 谁让老板常改需求呢 你懂得

不使用v4包内的fragment 而想使用 v4包的ViewPager
FragmentStatePagerAdapter

/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yangdc.common.fragment.base;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * Implementation of {@link android.support.v4.view.PagerAdapter} that
 * represents each page as a {@link Fragment} that is persistently
 * kept in the fragment manager as long as the user can return to the page.
 *
 * <p>This version of the pager is best for use when there are a handful of
 * typically more static fragments to be paged through, such as a set of tabs.
 * The fragment of each page the user visits will be kept in memory, though its
 * view hierarchy may be destroyed when not visible.  This can result in using
 * a significant amount of memory since fragment instances can hold on to an
 * arbitrary amount of state.  For larger sets of pages, consider
 * {@link FragmentStatePagerAdapter}.
 *
 * <p>When using FragmentPagerAdapter the host ViewPager must have a
 * valid ID set.</p>
 *
 * <p>Subclasses only need to implement {@link #getItem(int)}
 * and {@link #getCount()} to have a working adapter.
 *
 * <p>Here is an example implementation of a pager containing fragments of
 * lists:
 *
 * {@sample development/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentPagerSupport.java
 *      complete}
 *
 * <p>The <code>R.layout.fragment_pager</code> resource of the top-level fragment is:
 *
 * {@sample development/samples/Support4Demos/res/layout/fragment_pager.xml
 *      complete}
 *
 * <p>The <code>R.layout.fragment_pager_list</code> resource containing each
 * individual fragment‘s layout is:
 *
 * {@sample development/samples/Support4Demos/res/layout/fragment_pager_list.xml
 *      complete}
 */
public abstract class FragmentPagerAdapter extends PagerAdapter {
    private static final String TAG = "FragmentPagerAdapter";
    private static final boolean DEBUG = false;

    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;
    private Fragment mCurrentPrimaryItem = null;

    public FragmentPagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    @Override
    public void startUpdate(ViewGroup container) {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        final long itemId = getItemId(position);

        // Do we already have this fragment?

String name = makeFragmentName(container.getId(), itemId); Fragment fragment = mFragmentManager.findFragmentByTag(name); if (fragment != null) { if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment); mCurTransaction.attach(fragment); } else { fragment = getItem(position); if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment); mCurTransaction.add(container.getId(), fragment, makeFragmentName(container.getId(), itemId)); } if (fragment != mCurrentPrimaryItem) { fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); } return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object + " v=" + ((Fragment)object).getView()); mCurTransaction.detach((Fragment)object); } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { Fragment fragment = (Fragment)object; if (fragment != mCurrentPrimaryItem) { if (mCurrentPrimaryItem != null) { mCurrentPrimaryItem.setMenuVisibility(false); mCurrentPrimaryItem.setUserVisibleHint(false); } if (fragment != null) { fragment.setMenuVisibility(true); fragment.setUserVisibleHint(true); } mCurrentPrimaryItem = fragment; } } @Override public void finishUpdate(ViewGroup container) { if (mCurTransaction != null) { mCurTransaction.commitAllowingStateLoss(); mCurTransaction = null; mFragmentManager.executePendingTransactions(); } } @Override public boolean isViewFromObject(View view, Object object) { return ((Fragment)object).getView() == view; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } /** * Return a unique identifier for the item at the given position. * * <p>The default implementation returns the given position. * Subclasses should override this method if the positions of items can change.</p> * * @param position Position within this adapter * @return Unique identifier for the item at position */ public long getItemId(int position) { return position; } private static String makeFragmentName(int viewId, long id) { return "android:switcher:" + viewId + ":" + id; } } /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package yangdc.common.fragment.base; import java.util.ArrayList; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.view.View; import android.view.ViewGroup; /** * Implementation of {@link android.support.v4.view.PagerAdapter} that * uses a {@link Fragment} to manage each page. This class also handles * saving and restoring of fragment‘s state. * * <p>This version of the pager is more useful when there are a large number * of pages, working more like a list view. When pages are not visible to * the user, their entire fragment may be destroyed, only keeping the saved * state of that fragment. This allows the pager to hold on to much less * memory associated with each visited page as compared to * {@link FragmentPagerAdapter} at the cost of potentially more overhead when * switching between pages. * * <p>When using FragmentPagerAdapter the host ViewPager must have a * valid ID set.</p> * * <p>Subclasses only need to implement {@link #getItem(int)} * and {@link #getCount()} to have a working adapter. * * <p>Here is an example implementation of a pager containing fragments of * lists: * * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/FragmentStatePagerSupport.java * complete} * * <p>The <code>R.layout.fragment_pager</code> resource of the top-level fragment is: * * {@sample development/samples/Support13Demos/res/layout/fragment_pager.xml * complete} * * <p>The <code>R.layout.fragment_pager_list</code> resource containing each * individual fragment‘s layout is: * * {@sample development/samples/Support13Demos/res/layout/fragment_pager_list.xml * complete} */ public abstract class FragmentStatePagerAdapter extends PagerAdapter { private static final String TAG = "FragmentStatePagerAdapter"; private static final boolean DEBUG = false; private final FragmentManager mFragmentManager; private FragmentTransaction mCurTransaction = null; private ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>(); private ArrayList<Fragment> mFragments = new ArrayList<Fragment>(); private Fragment mCurrentPrimaryItem = null; public FragmentStatePagerAdapter(FragmentManager fm) { mFragmentManager = fm; } /** * Return the Fragment associated with a specified position. */ public abstract Fragment getItem(int position); @Override public void startUpdate(ViewGroup container) { } @Override public Object instantiateItem(ViewGroup container, int position) { // If we already have this item instantiated, there is nothing // to do. This can happen when we are restoring the entire pager // from its saved state, where the fragment manager has already // taken care of restoring the fragments we previously had instantiated. if (mFragments.size() > position) { Fragment f = mFragments.get(position); if (f != null) { return f; } } if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } Fragment fragment = getItem(position); if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment); if (mSavedState.size() > position) { Fragment.SavedState fss = mSavedState.get(position); if (fss != null) { fragment.setInitialSavedState(fss); } } while (mFragments.size() <= position) { mFragments.add(null); } fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); mFragments.set(position, fragment); mCurTransaction.add(container.getId(), fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { Fragment fragment = (Fragment)object; if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object + " v=" + ((Fragment)object).getView()); while (mSavedState.size() <= position) { mSavedState.add(null); } mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment)); mFragments.set(position, null); mCurTransaction.remove(fragment); } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { Fragment fragment = (Fragment)object; if (fragment != mCurrentPrimaryItem) { if (mCurrentPrimaryItem != null) { mCurrentPrimaryItem.setMenuVisibility(false); mCurrentPrimaryItem.setUserVisibleHint(false); } if (fragment != null) { fragment.setMenuVisibility(true); fragment.setUserVisibleHint(true); } mCurrentPrimaryItem = fragment; } } @Override public void finishUpdate(ViewGroup container) { if (mCurTransaction != null) { mCurTransaction.commitAllowingStateLoss(); mCurTransaction = null; mFragmentManager.executePendingTransactions(); } } @Override public boolean isViewFromObject(View view, Object object) { return ((Fragment)object).getView() == view; } @Override public Parcelable saveState() { Bundle state = null; if (mSavedState.size() > 0) { state = new Bundle(); Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()]; mSavedState.toArray(fss); state.putParcelableArray("states", fss); } for (int i=0; i<mFragments.size(); i++) { Fragment f = mFragments.get(i); if (f != null) { if (state == null) { state = new Bundle(); } String key = "f" + i; mFragmentManager.putFragment(state, key, f); } } return state; } @Override public void restoreState(Parcelable state, ClassLoader loader) { if (state != null) { Bundle bundle = (Bundle)state; bundle.setClassLoader(loader); Parcelable[] fss = bundle.getParcelableArray("states"); mSavedState.clear(); mFragments.clear(); if (fss != null) { for (int i=0; i<fss.length; i++) { mSavedState.add((Fragment.SavedState)fss[i]); } } Iterable<String> keys = bundle.keySet(); for (String key: keys) { if (key.startsWith("f")) { int index = Integer.parseInt(key.substring(1)); Fragment f = mFragmentManager.getFragment(bundle, key); if (f != null) { while (mFragments.size() <= index) { mFragments.add(null); } f.setMenuVisibility(false); mFragments.set(index, f); } else { Log.w(TAG, "Bad fragment at key " + key); } } } } } }

BitmapUtils 二次封装 主要是 有部分url 没有http部分 做少许处理

package yangdc.common.utils;

import yangdc.common.AppContext;
import yangdc.common.Constants;
import yangdc.common.R;
import android.content.Context;
import android.widget.ImageView;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.core.BitmapSize;

public class BitmapUtil extends BitmapUtils{


    static BitmapDisplayConfig bitmapDisplayConfig = getBitmapDisplayConfig();

    public BitmapUtil(Context context) {
        this(context, null);
    }
    public static BitmapDisplayConfig getBitmapDisplayConfig() {
        if (bitmapDisplayConfig == null) {
            bitmapDisplayConfig = new BitmapDisplayConfig();
            bitmapDisplayConfig.setLoadingDrawable(AppContext.getContext().getResources().getDrawable(R.drawable.image_loading));
            bitmapDisplayConfig.setLoadFailedDrawable(AppContext.getContext().getResources().getDrawable(R.drawable.image_fail));
        }
        return bitmapDisplayConfig;
    }
     public BitmapUtil(Context context, String diskCachePath) {
         super(context, diskCachePath);
     }
     public void display(ImageView imageView,String url){
        imageView.setImageResource(R.drawable.empty_photo);
        if (StringUtils.isEmpty(url)) {
            return;
        }
        if (!url.startsWith("http")) {
            url = Constants.image_url +"/"+ url;
        }
//      BitmapSize bitmapSize = new BitmapSize(imageView.getLayoutParams().width, imageView.getLayoutParams().height);
//      bitmapDisplayConfig.setBitmapMaxSize(bitmapSize);
        super.display(imageView, url ,bitmapDisplayConfig);
     }
}

好了 去吃中午饭了。。。。









以上是关于代码二次封装-xUtils(android)的主要内容,如果未能解决你的问题,请参考以下文章

Android使用xUtils3上传图片报错解决:java.lang.ArrayIndexOutOfBoundsException: 70918

xUtils

Android 最火框架XUtils之注解机制具体解释

Android 最火框架XUtils之注解机制具体解释

Android第九讲笔记(xUtils框架,Gson框架)

XUtils BitmapUtils 改造以加入drawable支持