viewpager+fragment+listview registerForContextMenu

1.需求描述

viewpager  +  fragment   ,每個fragment 中的佈局都是listview ,listview 支持點擊(OnItemClick)和長按(registerForContextMenu),  點擊進入詳情頁面;每次長按彈出 MeunItem 之後,點擊MeunItem  彈出提示框提示用戶是否刪除,用戶點擊確定即可刪除該行


       2.問題描述

點擊事件沒問題的實現。可是長按出現了問題,每次長按彈出 MeunItem 之後,點擊MeunItem  彈出提示框提示用戶是否刪除,此時點擊刪除出現空指針,發現每次彈框的數量 是當前fragment 的預加載的數量,意思就是,當我點擊彈出框的取消按鈕或者 點提示框外部區域,這個提示框消失了,後面還有提示框,而且數量正好是當前fragment 所決定的。而當前面的一個或者2個提示框消失以後,再點擊刪除就沒有出現空指針,那麼問題應該就是和預加載有很大的關係了。

3.解決方法

(1)fragment 是通過newInstance 來new 出來,每次傳入當前位置,在當前fragment 記下傳入的position
public static ServiceOrderFragment newInstance(int position) {
ServiceOrderFragment f = new ServiceOrderFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
 }



2)獲取當前fragment 在viewpager 中的位置,可以在 fragment 的宿主activity中 公開一個方法,獲取位置 
public int getCurFragmentIndex() {
       return mViewPager.getCurrentItem();
    }
(3)在當前fragment 的 onContextItemSelected  方法中,
   int curIndex = ((ServiceOrderActivity) getActivity()).getCurFragmentIndex();  
獲取到當前fragment 所在位置,然後用  newInstance(int position記錄的position  和 curIndex 作對比,相等的時候纔去 顯示 提示框。
   這樣,就可以控制彈框到底屬於哪個fragment 了。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章