java.lang.IllegalStateException:活动已被破坏 [英] java.lang.IllegalStateException: Activity has been destroyed

查看:262
本文介绍了java.lang.IllegalStateException:活动已被破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与Robolectric工作,我是很新的Andr​​oid系统。我使用的活动做了第一次测试类。它的工作很好。 现在,我希望做一个试验片段。

Working with Robolectric , I'm very new to android. I made a first test class using Activity. It worked nicely. Now I want make a test for fragment.

@RunWith(RobolectricTestRunner.class)
public class LoginFragmentTest {
    private LoginFragment fragment;

    @Before
    public void setup() {
        fragment = new LoginFragment();
        startFragment(fragment);
        assertThat(fragment, notNullValue());
        assertThat(fragment.getActivity(), notNullValue());
    }

    private void startFragment(LoginFragment fragment) {
        FragmentManager fragmentManager = new FragmentActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(fragment, null);
        fragmentTransaction.commit();
    }

    @Test
    public void login() {
        EditText idEditText = (EditText)fragment.getActivity().findViewById(R.id.main_id);
        assertThat(idEditText, notNullValue());
    }
}

这是我的第一个测试类片段类。它抛出

This is my first test class for Fragment class. It throws

"java.lang.IllegalStateException: Activity has been destroyed" in startFragment#fragmentTransaction.commit().

任何人知道如何解决这一问题?

Anyone knows how to fix this ?

您可以找到全部源从 https://github.com/msbaek/frame-test

在此先感谢!

推荐答案

该片段应该是从活动中显示出来。该流程应该是:

The fragments are supposed to be displayed from an Activity. The flow should be:

  • 在一个FragmentActivity类分配一个新片段对象
  • 获得片段管理者增加新分配的片段

在你的情况,你不必到实体经济活动的连接。你分配新FragmentActivity(一FragmentActivity),并得到了支持经理。虽然这编译没有真正的活动能够管理你的片段。片段可以在已经显示的活动被添加并在这里它不是这种情况。

In your case you do not have a connection to a real activity. You allocate a FragmentActivity with new FragmentActivity() and try to get the support manager. While this compiles there is no "real" activity able to manage your fragment. Fragments can be added on activities already displayed and here it's not the case.

我建议你阅读这个页面,因为它解释了这些事情非常好:的http://开发商.android.com /引导/组件/ fragments.html

I recommend reading this page as it explains these things very well: http://developer.android.com/guide/components/fragments.html

这篇关于java.lang.IllegalStateException:活动已被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆