如何在我的片段中保存接口的状态?

时间:2014-01-16 16:00:54

标签: android interface fragment dialogfragment

我有Activity使用ViewPagerFragment类中创建三个ViewPager我将Fragment设置为setRetainInstace(true);当它们被创建时。

在我的一个Fragment内,我正在显示一些可编辑的信息。此Fragment会启动DialogFragment来修改信息。

当用户没有更改方向时,我可以更新信息并将结果发送回视图中的片段,但是,一旦我更改了方向,并对信息进行更新Interface我在DialogFragment 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);

}

}

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找onActivityCreated(Bundle bundle);,这是FragmentActivity的等效onRestoreSavedInstanceState(Bundle bundle);

来自文档:

  

public void onActivityCreated(Bundle savedInstanceState)已添加   API等级11

     

在创建片段活动时调用此方法   片段的视图层次结构实例化。它可以用来做最后的   这些部分就位后进行初始化,例如检索   观点或恢复状态。它对使用的片段也很有用   setRetainInstance(boolean)保留它们的实例,就像这个回调一样   告诉片段何时与新活动完全关联   实例。这是在onCreateView(LayoutInflater,ViewGroup,   Bundle)和onViewStateRestored(Bundle)之前。参数   savedInstanceState如果正在从a重新创建片段   以前保存的州,这是州。

当您的片段在方向更改时被销毁时,将其状态保存为活动Bundle中的名称值对,然后在需要重新创建时,在此方法中实例化新的Interface,并且设置相应的字段/检索新Fragment实例中的parcelable。