代码二次封装-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);
     }
}

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

时间: 2024-10-17 08:22:34

代码二次封装-xUtils(android)的相关文章

毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选

毕加索的艺术--Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选 官网: http://square.github.io/picasso/ 我们在上篇OkHttp的时候说过这个Picasso,学名毕加索,是Square公司开源的一个Android图形缓存库,而且使用起来也是非常的简单,只要一行代码就轻松搞定了,你会问,为什么不介绍一下Glide?其实Glide我有时间也是会介绍的,刚好上篇我们用到了Picasso,

Android 应用程序集成FaceBook 登录及二次封装

1.首先在Facebook 开发者平台注册一个账号 https://developers.facebook.com/ 开发者后台  https://developers.facebook.com/apps 2.创建账号并且获得 APP ID 图一 图二 图三 图四 图五 3.获取app签名的Key Hashes 值(两种方式) 3.1方法1: 1 package com.pegasus.map.presentation.utils; 2 import android.content.Contex

Android 完美对BaseAdapter进行二次封装

在开发列表的界面的时候经常会重写BaseAdapter,利用网上的知识点技巧,自己对它进行了二次封装方便以后在项目中再次使用.使用起来方便得很. 当然如何你看了代码可以的话,也可以对ExpandableListAdapter同样的封装! 使用自定义BaseAdapter: package com.cyy.myandroid; import android.content.Context; import android.provider.ContactsContract.Data; import

对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)

首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6+,iOS 6+, android 4+.两套运行时,同样的调用方式,可供

android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件

网络请求是全部App都不可缺少的功能,假设每次开发都重写一次网络请求或者将曾经的代码拷贝到新的App中,不是非常合理,出于此目的,我希望将整个网络请求框架独立出来,与业务逻辑分隔开,这样就能够避免每次都要又一次编写网络请求,于是基于我比較熟悉的asynchttpclient又一次二次封装了一个网络请求框架. 思路:网络请求层唯一的功能就是发送请求,接收响应数据,请求取消,cookie处理这几个功能,二次助封装后这些功能能够直接调用封装好的方法就可以. 二次助封装代码例如以下: 1.功能接口: /

也谈Volley的二次封装

产品中使用Volley框架已有多时,本身已有良好封装的Volley确实给程序开发带来了很多便利与快捷.但随着产品功能的不断增加,服务器接口的不断复杂化,直接使用Volley原生的JSONObjectRequest已经导致Activity或Fragment层中耦合了大量的数据解析代码,同时当多处调用同一接口时,类似的数据解析代码还不可复用,导致大量重复代码的出现,已经让我越发地无法忍受.基于此,最近思考着对Volley原生的JSONObjectRequest(因为产品中目前和服务器交互所有的接口,

OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据

OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据 我们这片博文就来聊聊这个反响很不错的OkHttp了,标题是我恶搞的,本篇将着重详细的分析,探索OkHttp这个框架的使用和封装 一.追其原理 Android系统提供了两种HTTP通信类 HttpURLConnection HttpClient Google推荐使用HttpURLConnection,这个没必要多说,事实上,我这篇写的应该算是比较晚了,很多优秀的博文都已经提出了这些观

Android-Volley网络通信框架(二次封装数据请求和图片请求(包含处理请求队列和图片缓存))

1.回想 上篇 使用 Volley 的 JsonObjectRequest 和 ImageLoader 写了 电影列表的样例 2.重点 (1)封装Volley 内部 请求 类(请求队列,数据请求,图片请求,图片缓存) (2)封装 Response.Listener 和 Response.ErrorListener 回调函数 (3)用法 3.文件夹介绍 3.1 GsonRequset.java 自己定义Gson请求,直接将 Json字符串  实例化为 对象 3.2 VolleyApplicatio

android-async-http二次封装和调用

Android  android-async-http二次封装和调用 在开发过程中,网络请求这块的使我们经常遇到的一个问题,今天去github 网站上面学习android-async-http,觉得还是不错的  使用起来也比较简便   网络请求框架是一个不错的选择   方便大家一起共同讨论   QQ群:160373684 /** * * @类描述:android-async-http 进行封装的类 * @项目名称: * @包名: * @类名称:AndroidAsyncHttpHelper * @