片段中的 IllegalStateException

IllegalStateException in Fragment

我正在做一个 activity,其中包含一个片段。当 fragment1 上的一个按钮被按下时,fragment 1 变为 fragment2 但它说 IllegalStateException Activity has been destroyed

这是来自 Activity 容器的代码。

public class SeleccionEjercito extends FragmentActivity implements FragmentEjercito.listener {

Context contexto;
Fragment firsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seleccionejercito);
    // Crea una instancia de FragmentEjercito
    firsFragment = new FragmentEjercito();
    // Añadimos el fragmento al FrameLayout contenedor
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.fragment_container,firsFragment);
    ft.commit();
}

//metodo que hace la consulta a la base de datos y cambia el fragment
public void cambiarFragment()
{
    Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
            Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_menu_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void swap()
{
    FragmentSectorial secondFragement = new FragmentSectorial();
    //SeleccionEjercito s = new SeleccionEjercito();
    FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
    //ft.remove(firsFragment);
    ft.replace(R.id.fragment_container, secondFragement);
    ft.addToBackStack(null);
    ft.commit();
}

public void backSwap()
{
    swap();
}

}

这是第一个片段的代码。

public class FragmentEjercito extends Fragment {

Button test;
private static String LOGCAT = "LogsAndroid";
listener mCallBack;
Activity mActivity;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflamos la interfaz de usuario para este fragmento

    final View InputFragmentView = inflater.inflate(R.layout.fragment_ejercito, container, false);
    test = (Button) InputFragmentView.findViewById(R.id.bnTest);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallBack.backSwap();
        }
    });
    return InputFragmentView;
}

@Override
public void onAttach(Activity activity)
{
    mActivity = activity;
    super.onAttach(activity);
    mCallBack = (listener) activity;
}


@Override
public void onDetach() {
    super.onDetach();

    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

public interface listener
{
    public void backSwap();
}

}

这是第二个片段

public class FragmentSectorial extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_sectorial, container, false);
}

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);
}

我把logcat放在这里

11-12 03:01:36.301    3117-3117/armymovil E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Activity has been destroyed
        at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1399)
        at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
        at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
        at albertorollan.armymovil.SeleccionEjercito.swap(SeleccionEjercito.java:75)
        at albertorollan.armymovil.SeleccionEjercito.backSwap(SeleccionEjercito.java:80)
        at albertorollan.armymovil.FragmentEjercito.onClick(FragmentEjercito.java:38)
        at android.view.View.performClick(View.java:4240)
        at android.view.View$PerformClick.run(View.java:17721)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

很可能您正在尝试用片段 1 本身的片段 2 替换片段 1。 请尝试将 swap() 方法移至主 activity 并向片段交互添加侦听器。

一般来说,您不能用片段中的另一个片段替换片段。正如 Dobry 所说,使用一个监听器。您需要从 Activity 实现的片段中获得一个接口。

在片段中创建以下字段:

listener mCallback;
activity mActivity;

在片段中创建以下方法:

@Override
        public void onAttach(Activity activity) {
            mActivity=activity;
            super.onAttach(activity);
        mCallback = (listener) activity;
        }

在片段中创建如下接口:

public interface listener {
        public void backSwap();
    }

从片段中的 onCLick 中删除 swap() 并替换为

mCallback.backSwap();

将交换方法从片段移动到 seleccionEjercito。

修改activity的声明实现接口

public class SeleccionEjercito extends FragmentActivity implements fragmentEjercito.listener{  etc

最后在seleccionEjercito中创建如下方法

public void backSwap(){  swap();}

如果不让我知道,我希望这能奏效

1)首先需要使用fragment容器作为Layout(Frame, Linear等)

2) 比使用 FragmentManager.replace 代替 FragmentManager.add(在您的 MainActivity 中)

就这些!