2014-01-16 79 views
0

我有一個Activity,它使用ViewPagerViewPager類中創建三個Fragment s,當它們被創建時,我將Fragment s設置爲setRetainInstace(true);如何保存我的片段中的接口狀態?

在我的Fragment s之內,我顯示了一些可編輯的信息。此Fragment啓動DialogFragment來編輯信息。

當用戶未更改方向時,我可以更新信息並將結果發送回視圖中的片段,但是,一旦我更改了方向並更新了信息,我的Interface已附加在DialogFragment s onAttach()方法我得到NullPointerException

我不明白爲什麼,因爲每次啓動新的DialogFragment時總會調用onAttach()方法。

我應該如何解決這個問題? 我可以保存界面的狀態嗎?如果是的話如何?

這是我DialogFragment代碼: 的GenericDialogFragment類僅用於更改外觀

public class Fragment1 extends GenericDialogFragment implements WebServiceResult{ 



// ------------------------------------------------------------------------- 
// Member Variables 
//-------------------------------------------------------------------------- 
//Webservice Callback 
private WSRequest mActiveRequest = null; 
// The Current Context of the Application 
private Context mClassContext = null; 
// Interface reference for communication 
private static CommunicateResults communicateResults = null; 


// ------------------------------------------------------------------------- 
// New Instance Method 
//--------------------------------------------------------------------------  

public static Fragment1 newInstance(int userId, GenericObject [] objects, GenericGroup [] groups, Object currentObject){ 
    // Initialize a new Fragment1 
    Fragment1 fragment = new Fragment1(); 
    // Create a new Bundle 
    Bundle args = new Bundle(); 

    fragment.setArguments(args); 

    // Return the Fragment1 
    return fragment; 
} 

// ------------------------------------------------------------------------- 
// Class Functions/Methods 
//--------------------------------------------------------------------------  

// States that the Interface is attached to the parent activity 
@Override public void onAttach(Activity activity) 
{ 
    // Perform the Default Behavior 
    super.onAttach(activity); 
    Log.d("ONAttach()","On attach() is called"); 
    // Try 
    try{ 
     // Attach the interface to the activity 
     communicateResults = (CommunicateResults) ((MainActivity) getActivity()).findFragment(EditableFragment1.class); 

    }catch(Exception ex){ 
     // Print the stack trace 
     ex.printStackTrace(); 
    } 
} 

// States that the Dialog's View has been Created 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
    // Return the Inflated XML Layout 
    return inflater.inflate(R.layout.fragment1, container, false); 
} 

// States that the fragment has been created, last chance to update the UI 
@Override 
public void onActivityCreated(Bundle savedInstanceState){ 
    // Perform the Default behavior 
    super.onActivityCreated(savedInstanceState); 

    mClassContext = getActivity(); 

    // Get the Arguments passed into the Fragment instance 
    savedStateData = getArguments(); 

    // Reference all the UI Elements in the View  


    // Add listeners to the Button Widgets 


    // If the savedInstanceState is not null, get the current object 
    if(savedStateData != null){ 

     // Get the object out of the state data 
     mCurrentObject = savedStateData.getParcelable(STATE_DATA_CURRENT_OBJECT); 

    } 



} 


//----------------------------------------------------------------------------- 
// Webservice Callback methods 
//----------------------------------------------------------------------------- 

// States that the web service has succeeded 
@Override public void webserviceSucceeded(WebServiceBase finishedService, Object responseData) 
{ 

    Log.d("EDIT Object", responseData.toString()); 

    if(responseData != null){ 

     if(mDeletingObject){ 



      // Send Back to the object to remove 
      communicateResults.sendBackData(mCurrentObject, ACTION_DELETE); 

     }else{ 

      JSONObject tempObject = (JSONObject) responseData; 

      try{ 

       // Parse Data ... 



      }catch(Exception ex){ 

       ex.printStackTrace(); 
       // TODO: The Object was deleted from the Lest 
      } 

      // If we are creating a object, bundle the information to pass to the parent activity 
      if(mCreatingObject){ 

       // Create a new Workout Object 
       mCurrentObject = new Object(); 


       // Callback to Parent Activity to notify that data has changed 
       communicateResults.sendBackData(mCurrentObject, ACTION_CREATE); 

       // Else the Object was updated 
      }else{ 
       // Create a new Object 
       mCurrentObject = new Object(); 


       // Callback to Parent Activity to notify that data has changed 
       communicateResults.sendBackData(mCurrentObject, ACTION_UPDATE); 
      } 
     } 


    } 

    // Dismiss the fragment 


} 


// States that the web service has failed 
@Override 
public void webserviceFailed(WebServiceBase finishedService, 
     Object errorData) { 


    // Display the Error 
    displayErrorData(errorData); 

} 

}

+0

聽起來像你的Activity是你的接口,如果你使用onAttach(Activity activity);那麼爲什麼不直接使用(CastToInterface)getActivty();? – Submersed

+0

我的活動不是我的界面。該界面在我的Fragment中用可編輯的數據聲明。所以我在這個片段中創建一個接口,然後我在DialogFragment中實現它。我試圖做出這種改變,我得到了ClassCastException,因爲這會試圖將接口強制轉換爲我的Activity,其中未執行 –

+0

難題。你能發佈你的片段代碼嗎? – Submersed

回答

0

我認爲你正在尋找onActivityCreated(Bundle bundle);,這是Fragment相當於Activity班的onRestoreSavedInstanceState(Bundle bundle);

從文檔:

公共無效onActivityCreated(捆綁savedInstanceState)添加在 API級別11

片段的活動已創建時調用,這 片段的視圖層次實例化。一旦這些部分到位,它就可以用來執行最終的初始化 ,例如檢索 視圖或恢復狀態。對於使用setRetainInstance(boolean)來保留其實例的片段也很有用,因爲此回調告知片段何時與新活動 實例完全關聯。這是在onCreateView(LayoutInflater,ViewGroup, Bundle)之前和onViewStateRestored(Bundle)之前調用的。參數 savedInstanceState如果正在從 先前保存的狀態重新創建片段,則爲狀態。

當您的片段上的取向變化破壞,保存其作爲活動的Bundle名稱值對的狀態,那麼當需要重新創建它,實例化在這種方法的新Interface,並設置相應字段/檢索新的Fragment實例中的可分發內容。

+0

這裏有點困惑。如果每次創建新的DialogFragment時調用onAttach()方法,都不應該這樣嗎?或者這是我的Fragment中實現接口的問題? –

+0

不知道,我不得不看你是如何實現你的片段。 – Submersed

+0

Theres在片段中的一大堆代碼我會嘗試將它配對,所以我只分享你需要的東西。 –