【问题标题】:Activity is NULL in fragment, but not always in AndroidActivity 在片段中为 NULL,但在 Android 中并非总是如此
【发布时间】:2017-11-04 19:04:41
【问题描述】:

this.getActivity() 在我的片段中为 NULL,并且是从实际活动本身调用的。这并不总是发生,但我该如何解决?

sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));

EventActivity.java

eventsFragment.setUpEvents(getEventApplication());

EventsFragment.java

public void setUpEvents(Application application) {
      sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));

【问题讨论】:

  • 可能是调用的时机使它为空。此活动不会为空的保证之一是在调用onActivityCreated 时。此外,当 Fragment 与 Activity 分离时,Fragment 可能会存活一段时间,但 getActivity() 将为空。
  • 尝试将this.getActivity()更改为getActivity()
  • 为什么要删除 this 工作?
  • 因为this 是一个上下文。不属于片段。但它对它的容器 Activity 有影响。

标签: android android-fragments android-activity null


【解决方案1】:

只需从 this.getActivity() 中删除 this 并且如果您 extends 您的 Activity from AppCompatActivity 然后你必须使用相同的 如下所示

(AppCompatActivity) getActivity()

【讨论】:

    【解决方案2】:

    如果它的片段在父 Activity 中运行,那么在这种情况下,您可以在 EventActivity 中创建一个静态 Activity 对象并在片段中引用它而不是 getActivity(),因为它保证对片段可用。

    EventActivity.class

    protected Activity activity;
    
    onResume()
    {
        activity = this;
    }
    

    EventsFragment.class

    sportButton.setBackgroundColor(ViewHelper.getColor(EventActivity.activity));
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 2020-11-15
      • 2019-11-29
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 2019-12-07
      相关资源
      最近更新 更多