奇怪的范围行为

时间:2016-12-19 14:40:12

标签: android

所以我在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);
    ...
}

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

2 个答案:

答案 0 :(得分:0)

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

不在任何方法块中。您正准备在Activity准备好之前获取这些值。在加载AnotherFragment

之后调用的方法中移动它

答案 1 :(得分:0)

我打赌你得到NullPointerException,对吧?

这是因为您在Activity"准备就绪之前运行了代码"。

例如,Activtiy已准备就绪onCreate()。所以把我们的代码放在那里。

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

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myLayout);

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

您可以找到有关活动生命周期here的更多信息。

相关问题