此工程較BaiduLocationXMLFragmentDB相比:
1.滑動fragment自動刷新該fragment
2.下拉刷新fragment,上拉暫未實現
a.fragment切換刷新
1 . 由於運行進入是fragment1,會默認加載fragment2,但是加載的時候,獲取的得到地址天氣信息並沒有存入數據庫中,所以切換到fragment2時不會執行OncreateView再次加載fragment2(刷新方法寫在OncreateView),從而不會顯示剛存入數據庫的數據
首先說明下viewpager和fragment的特性
//默認值為1,及進入fragment1時,默認會加載fragment2, //設置為2時,會加載fragment2和fragment3 //且參數小於1會無效,會設置成默認值1 viewPager.setOffscreenPageLimit(1);
上述取消fragment預加載方法行不通。
使用以下方法:
參考:http://blog.csdn.net/yersterday/article/details/41008551
@Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { //當此fragment正當前顯示是,執行該操作, myListAdapter((List<HashMap<String, Object>>) getListItem(db.query()));//查詢數據庫數據,並刷新listview } else { // 相當於Fragment的onPause // System.out.println("ChatFragment ---setUserVisibleHint---isVisibleToUser - FALSE"); } }
從上面可以看出,在預加載fragment2時 不會執行setUserVisibleHint(boolean isVisibleToUser) 該方法,只有當切換到fragment2時才運行setUserVisibleHint(boolean isVisibleToUser)
2.下拉刷新
參考:http://blog.csdn.net/sziicool/article/details/18727999
package com.liucanwen.baidulocation.pull2refresh; import com.liucanwen.baidulocation.R; import com.liucanwen.baidulocation.R.id; import com.liucanwen.baidulocation.R.layout; import com.liucanwen.baidulocation.R.string; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.View.OnTouchListener; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; /** * 可進行下拉刷新的自定義控件。 * * @author guolin * */ public class RefreshableView extends LinearLayout implements OnTouchListener { /** * 下拉狀態 */ public static final int STATUS_PULL_TO_REFRESH = 0; /** * 釋放立即刷新狀態 */ public static final int STATUS_RELEASE_TO_REFRESH = 1; /** * 正在刷新狀態 */ public static final int STATUS_REFRESHING = 2; /** * 刷新完成或未刷新狀態 */ public static final int STATUS_REFRESH_FINISHED = 3; /** * 下拉頭部回滾的速度 */ public static final int SCROLL_SPEED = -20; /** * 一分鍾的毫秒值,用於判斷上次的更新時間 */ public static final long ONE_MINUTE = 60 * 1000; /** * 一小時的毫秒值,用於判斷上次的更新時間 */ public static final long ONE_HOUR = 60 * ONE_MINUTE; /** * 一天的毫秒值,用於判斷上次的更新時間 */ public static final long ONE_DAY = 24 * ONE_HOUR; /** * 一月的毫秒值,用於判斷上次的更新時間 */ public static final long ONE_MONTH = 30 * ONE_DAY; /** * 一年的毫秒值,用於判斷上次的更新時間 */ public static final long ONE_YEAR = 12 * ONE_MONTH; /** * 上次更新時間的字符串常量,用於作為SharedPreferences的鍵值 */ private static final String UPDATED_AT = "updated_at"; /** * 下拉刷新的回調接口 */ private PullToRefreshListener mListener; /** * 用於存儲上次更新時間 */ private SharedPreferences preferences; /** * 下拉頭的View */ private View header; /** * 需要去下拉刷新的ListView */ private ListView listView; /** * 刷新時顯示的進度條 */ private ProgressBar progressBar; /** * 指示下拉和釋放的箭頭 */ private ImageView arrow; /** * 指示下拉和釋放的文字描述 */ private TextView description; /** * 上次更新時間的文字描述 */ private TextView updateAt; /** * 下拉頭的布局參數 */ private MarginLayoutParams headerLayoutParams; /** * 上次更新時間的毫秒值 */ private long lastUpdateTime; /** * 為了防止不同界面的下拉刷新在上次更新時間上互相有沖突,使用id來做區分 */ private int mId = -1; /** * 下拉頭的高度 */ private int hideHeaderHeight; /** * 當前處理什么狀態,可選值有STATUS_PULL_TO_REFRESH, STATUS_RELEASE_TO_REFRESH, * STATUS_REFRESHING 和 STATUS_REFRESH_FINISHED */ private int currentStatus = STATUS_REFRESH_FINISHED;; /** * 記錄上一次的狀態是什么,避免進行重復操作 */ private int lastStatus = currentStatus; /** * 手指按下時的屏幕縱坐標 */ private float yDown; /** * 在被判定為滾動之前用戶手指可以移動的最大值。 */ private int touchSlop; /** * 是否已加載過一次layout,這里onLayout中的初始化只需加載一次 */ private boolean loadOnce; /** * 當前是否可以下拉,只有ListView滾動到頭的時候才允許下拉 */ private boolean ableToPull; /** * 下拉刷新控件的構造函數,會在運行時動態添加一個下拉頭的布局。 * * @param context * @param attrs */ public RefreshableView(Context context, AttributeSet attrs) { super(context, attrs); preferences = PreferenceManager.getDefaultSharedPreferences(context); header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true); progressBar = (ProgressBar) header.findViewById(R.id.progress_bar); arrow = (ImageView) header.findViewById(R.id.arrow); description = (TextView) header.findViewById(R.id.description); updateAt = (TextView) header.findViewById(R.id.updated_at); touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); refreshUpdatedAtValue(); setOrientation(VERTICAL); addView(header, 0); } /** * 進行一些關鍵性的初始化操作,比如:將下拉頭向上偏移進行隱藏,給ListView注冊touch事件。 */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (changed && !loadOnce) { hideHeaderHeight = -header.getHeight(); headerLayoutParams = (MarginLayoutParams) header.getLayoutParams(); headerLayoutParams.topMargin = hideHeaderHeight; listView = (ListView) getChildAt(1); listView.setOnTouchListener(this); loadOnce = true; } } /** * 當ListView被觸摸時調用,其中處理了各種下拉刷新的具體邏輯。 */ @Override public boolean onTouch(View v, MotionEvent event) { setIsAbleToPull(event); if (ableToPull) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: yDown = event.getRawY(); break; case MotionEvent.ACTION_MOVE: float yMove = event.getRawY(); int distance = (int) (yMove - yDown); // 如果手指是下滑狀態,並且下拉頭是完全隱藏的,就屏蔽下拉事件 if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) { return false; } if (distance < touchSlop) { return false; } if (currentStatus != STATUS_REFRESHING) { if (headerLayoutParams.topMargin > 0) { currentStatus = STATUS_RELEASE_TO_REFRESH; } else { currentStatus = STATUS_PULL_TO_REFRESH; } // 通過偏移下拉頭的topMargin值,來實現下拉效果 headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight; header.setLayoutParams(headerLayoutParams); } break; case MotionEvent.ACTION_UP: default: if (currentStatus == STATUS_RELEASE_TO_REFRESH) { // 松手時如果是釋放立即刷新狀態,就去調用正在刷新的任務 new RefreshingTask().execute(); } else if (currentStatus == STATUS_PULL_TO_REFRESH) { // 松手時如果是下拉狀態,就去調用隱藏下拉頭的任務 new HideHeaderTask().execute(); } break; } // 時刻記得更新下拉頭中的信息 if (currentStatus == STATUS_PULL_TO_REFRESH || currentStatus == STATUS_RELEASE_TO_REFRESH) { updateHeaderView(); // 當前正處於下拉或釋放狀態,要讓ListView失去焦點,否則被點擊的那一項會一直處於選中狀態 listView.setPressed(false); listView.setFocusable(false); listView.setFocusableInTouchMode(false); lastStatus = currentStatus; // 當前正處於下拉或釋放狀態,通過返回true屏蔽掉ListView的滾動事件 return true; } } return false; } /** * 給下拉刷新控件注冊一個監聽器。 * * @param listener * 監聽器的實現。 * @param id * 為了防止不同界面的下拉刷新在上次更新時間上互相有沖突, 請不同界面在注冊下拉刷新監聽器時一定要傳入不同的id。 */ public void setOnRefreshListener(PullToRefreshListener listener, int id) { mListener = listener; mId = id; } /** * 當所有的刷新邏輯完成后,記錄調用一下,否則你的ListView將一直處於正在刷新狀態。 */ public void finishRefreshing() { currentStatus = STATUS_REFRESH_FINISHED; preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit(); new HideHeaderTask().execute(); } /** * 根據當前ListView的滾動狀態來設定 {@link #ableToPull} * 的值,每次都需要在onTouch中第一個執行,這樣可以判斷出當前應該是滾動ListView,還是應該進行下拉。 * * @param event */ private void setIsAbleToPull(MotionEvent event) { View firstChild = listView.getChildAt(0); if (firstChild != null) { int firstVisiblePos = listView.getFirstVisiblePosition(); if (firstVisiblePos == 0 && firstChild.getTop() == 0) { if (!ableToPull) { yDown = event.getRawY(); } // 如果首個元素的上邊緣,距離父布局值為0,就說明ListView滾動到了最頂部,此時應該允許下拉刷新 ableToPull = true; } else { if (headerLayoutParams.topMargin != hideHeaderHeight) { headerLayoutParams.topMargin = hideHeaderHeight; header.setLayoutParams(headerLayoutParams); } ableToPull = false; } } else { // 如果ListView中沒有元素,也應該允許下拉刷新 ableToPull = true; } } /** * 更新下拉頭中的信息。 */ private void updateHeaderView() { if (lastStatus != currentStatus) { if (currentStatus == STATUS_PULL_TO_REFRESH) { description.setText(getResources().getString(R.string.pull_to_refresh)); arrow.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); rotateArrow(); } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) { description.setText(getResources().getString(R.string.release_to_refresh)); arrow.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); rotateArrow(); } else if (currentStatus == STATUS_REFRESHING) { description.setText(getResources().getString(R.string.refreshing)); progressBar.setVisibility(View.VISIBLE); arrow.clearAnimation(); arrow.setVisibility(View.GONE); } refreshUpdatedAtValue(); } } /** * 根據當前的狀態來旋轉箭頭。 */ private void rotateArrow() { float pivotX = arrow.getWidth() / 2f; float pivotY = arrow.getHeight() / 2f; float fromDegrees = 0f; float toDegrees = 0f; if (currentStatus == STATUS_PULL_TO_REFRESH) { fromDegrees = 180f; toDegrees = 360f; } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) { fromDegrees = 0f; toDegrees = 180f; } RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY); animation.setDuration(100); animation.setFillAfter(true); arrow.startAnimation(animation); } /** * 刷新下拉頭中上次更新時間的文字描述。 */ private void refreshUpdatedAtValue() { lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1); long currentTime = System.currentTimeMillis(); long timePassed = currentTime - lastUpdateTime; long timeIntoFormat; String updateAtValue; if (lastUpdateTime == -1) { updateAtValue = getResources().getString(R.string.not_updated_yet); } else if (timePassed < 0) { updateAtValue = getResources().getString(R.string.time_error); } else if (timePassed < ONE_MINUTE) { updateAtValue = getResources().getString(R.string.updated_just_now); } else if (timePassed < ONE_HOUR) { timeIntoFormat = timePassed / ONE_MINUTE; String value = timeIntoFormat + "分鍾"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else if (timePassed < ONE_DAY) { timeIntoFormat = timePassed / ONE_HOUR; String value = timeIntoFormat + "小時"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else if (timePassed < ONE_MONTH) { timeIntoFormat = timePassed / ONE_DAY; String value = timeIntoFormat + "天"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else if (timePassed < ONE_YEAR) { timeIntoFormat = timePassed / ONE_MONTH; String value = timeIntoFormat + "個月"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } else { timeIntoFormat = timePassed / ONE_YEAR; String value = timeIntoFormat + "年"; updateAtValue = String.format(getResources().getString(R.string.updated_at), value); } updateAt.setText(updateAtValue); } /** * 正在刷新的任務,在此任務中會去回調注冊進來的下拉刷新監聽器。 * * @author guolin */ class RefreshingTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { int topMargin = headerLayoutParams.topMargin; while (true) { topMargin = topMargin + SCROLL_SPEED; if (topMargin <= 0) { topMargin = 0; break; } publishProgress(topMargin); sleep(10); } currentStatus = STATUS_REFRESHING; publishProgress(0); if (mListener != null) { mListener.onRefresh(); } return null; } @Override protected void onProgressUpdate(Integer... topMargin) { updateHeaderView(); headerLayoutParams.topMargin = topMargin[0]; header.setLayoutParams(headerLayoutParams); } protected void onPostExecute(){ Toast.makeText(getContext(), "haha", Toast.LENGTH_LONG); } } /** * 隱藏下拉頭的任務,當未進行下拉刷新或下拉刷新完成后,此任務將會使下拉頭重新隱藏。 * * @author guolin */ class HideHeaderTask extends AsyncTask<Void, Integer, Integer> { @Override protected Integer doInBackground(Void... params) { int topMargin = headerLayoutParams.topMargin; while (true) { topMargin = topMargin + SCROLL_SPEED; if (topMargin <= hideHeaderHeight) { topMargin = hideHeaderHeight; break; } publishProgress(topMargin); sleep(10); } return topMargin; } @Override protected void onProgressUpdate(Integer... topMargin) { headerLayoutParams.topMargin = topMargin[0]; header.setLayoutParams(headerLayoutParams); } @Override protected void onPostExecute(Integer topMargin) { headerLayoutParams.topMargin = topMargin; header.setLayoutParams(headerLayoutParams); currentStatus = STATUS_REFRESH_FINISHED; } } /** * 使當前線程睡眠指定的毫秒數。 * * @param time * 指定當前線程睡眠多久,以毫秒為單位 */ private void sleep(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 下拉刷新的監聽器,使用下拉刷新的地方應該注冊此監聽器來獲取刷新回調。 * * @author guolin */ public interface PullToRefreshListener { /** * 刷新時會去回調此方法,在方法內編寫具體的刷新邏輯。注意此方法是在子線程中調用的, 你可以不必另開線程來進行耗時操作。 */ void onRefresh(); } }
直接在onfresh方法中直接執行
myListAdapter((List<HashMap<String, Object>>)
getListItem(db.query()));
語句會報

問題是:Only the original thread that can created a view hierarchy can touch its view
也就是Android不允許子線程刷新UI,
解決辦法:要添加一個Handler來實現刷新。
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { System.out.println("-------->>>>Fragment2---onCreateView"); if (rootView == null) { rootView = inflater.inflate(R.layout.fragment2, container, false); } // 緩存的rootView需要判斷是否已經被加過parent, // 如果有parent需要從parent刪除,要不然會發生這個rootview已經有parent的錯誤。 ViewGroup parent = (ViewGroup) rootView.getParent(); if (parent != null) { parent.removeView(rootView); } Context context = getActivity().getApplicationContext(); db = new DBManager(context); tempList = getListItem(db.query()); refreshableView = (RefreshableView) rootView .findViewById(R.id.refreshable_view); myListAdapter((List<HashMap<String, Object>>) getListItem(db.query())); refreshableView.setOnRefreshListener(new PullToRefreshListener() { @Override public void onRefresh() { try { // 自己添加的更新事件 // myListAdapter((List<HashMap<String, Object>>) // getListItem(db.query())); if (mThread == null) { mThread = new Thread(runnable); mThread.start();// 線程啟動 } Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } refreshableView.finishRefreshing(); } }, 0); return rootView; } Runnable runnable = new Runnable() { @Override public void run() {// run()在新的線程中運行 List<HashMap<String, Object>> templist = getListItem(db.query()); mHandler.obtainMessage(MSG_SUCCESS, templist).sendToTarget();// // 獲取成功,向ui線程發送 } }; final Handler mHandler = new Handler() { @SuppressWarnings("unchecked") public void handleMessage(Message msg) {// 此方法在ui線程運行 switch (msg.what) { case MSG_SUCCESS: myListAdapter((List<HashMap<String, Object>>) msg.obj); break; default: break; } } };

