奇怪的范围行为

尼亚·帕尼拉格(Neah Panilag)

因此,我在android中有此代码(活动中的接口方法实现),该应用程序运行得很好。

public void Clicks(int clickCounter) {
    FragmentManager fragmentManager = getFragmentManager();
    AnotherFragment another_fragment = (AnotherFragment) fragmentManager.findFragmentById(R.id.another_fragment);
    another_fragment.showClicks(clickCounter);
}

现在,当我尝试将fragmentManager和another_fragment声明为类变量时,如下所示:

public class MainActivity extends AppCompatActivity implements FragmentInterface{
    FragmentManager fragmentManager;
    AnotherFragment anotherFragment;

    fragmentManager = getFragmentManager();
    anotherFragment = (AnotherFragment) fragmentManager.findFragmentById(R.id.another_fragment);
    ...
}

它会导致应用崩溃。为什么会这样呢?

Rohit5k2
fragmentManager = getFragmentManager();
anotherFragment = (AnotherFragment) fragmentManager.findFragmentById(R.id.another_fragment);

不在任何方法块中。您正在尝试在“活动”准备就绪之前获取这些值。将其移动到加载时调用的方法中AnotherFragment

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章