代码二次封装-xUtils(android)
通常我们会引用很多lib
而且会出现lib 与我们的功能仅仅差一点点 这种情况我们最好不要去改动源代码 而是进行二次封装
举例我使用 xUtils的二次封装 此处说明我是搞ios的 这个是android 今天mac 机子没网 蛋疼
使用到pulltorefresh 和 xUtils
- 网络封装
因为此处是没有文件处理所以我把參数转换里面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 应用程序集成Google 登录及二次封装
谷歌登录API: https://developers.google.com/identity/sign-in/android/ 1.注册并且登录google网站 https://accounts. ...
- Android 应用程序集成FaceBook 登录及二次封装
1.首先在Facebook 开发者平台注册一个账号 https://developers.facebook.com/ 开发者后台 https://developers.facebook.com/ap ...
- 毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选
毕加索的艺术--Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选 官网: http://square.github.i ...
- 社会化登录分享-Android SDK的二次封装和使用
本系列文章将第三方的登录分享功能进行二次封装,统一接口调用,简化了接不同平台登录分享的步骤. 0 系列文章 系列一 Android SDK的二次封装和使用 系列二 源码解析 系列三 微信SDK接入 系 ...
- 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)
前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...
- 对百度WebUploader的二次封装,精简前端代码之图片预览上传(两句代码搞定上传)
前言 本篇文章上一篇: 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传) 此篇是在上面的基础上扩展出来专门上传图片的控件封装. 首先我们看看效果: 正文 使用方式同 ...
- android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件
网络请求是全部App都不可缺少的功能,假设每次开发都重写一次网络请求或者将曾经的代码拷贝到新的App中,不是非常合理,出于此目的,我希望将整个网络请求框架独立出来,与业务逻辑分隔开,这样就能够避免每次 ...
- volley二次封装
产品中使用Volley框架已有多时,本身已有良好封装的Volley确实给程序开发带来了很多便利与快捷.但随着产品功能的不断增加,服务器接口的不断复杂化,直接使用Volley原生的JSONObjectR ...
- .Net Framework下对Dapper二次封装迁移到.Net Core2.0遇到的问题以及对Dapper的封装介绍
今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...
随机推荐
- Ubuntu apt-get方式安装Subversion
按照官方文档 http://subversion.apache.org/packages.html 使用apt-get安装方式: 1.安装Subversion: sudo apt-get instal ...
- js 暂时性死区
1.概念 在代码块内,使用let.const命令声明变量之前,该变量都是不可用的.这在语法上,称为“暂时性死区”(temporal dead zone,简称 TDZ). 2.注意 “暂时性死区”也意味 ...
- [Python]网络爬虫(八):糗事百科的网络爬虫(v0.2)源码及解析
转自:http://blog.csdn.net/pleasecallmewhy/article/details/8932310 项目内容: 用Python写的糗事百科的网络爬虫. 使用方法: 新建一个 ...
- MVC时间对比及时间范围判断
方法一:使用DateTime.Compare 方法 public static int Compare( DateTime t1, DateTime t2 ) t1 早于 t2:小于零t1 与 t2 ...
- wso2esb安装及helloworld
1.系统环境 Ubuntu12.04 192.168.0.97 root/password找管理员 Ubuntu12.04 192.168.0.99 root/password ...
- Tomcat 签名认证配置简例
在项目的web.xml中增加 <security-constraint> <web-resource-collection> <web-resource-name> ...
- 【laravel5.4】vue分页删除
1.a标签执行ajax删除,后台删除成功后,执行vue分页对象删除对应数据 VUE.js
- 【微信小程序】用户首次进入小程序拒绝授权,如何再次调用授权页面,获取用户信息userInfo
前言:微信小程序的app.js里面,最少有2个接口,一个wx.login:一个是wx.getUserInfo: 前者得到腾讯给我们的微信用户唯一的code,通过code获取openid,这个不需要用户 ...
- 从gentoo回归Arch,上组图
Arch一直在我笔记本里边,只是玩gentoo时我不进Arch了,现在回归Arch,升级到了最新,用上了gentoo的最新的2.6.31内核(自己配置,无initrd),引导程序用的grub4dos: ...
- Falsk-信号
Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为. 安装:pip3 install blinker request_started = _sign ...