代码之家  ›  专栏  ›  技术社区  ›  Rares Stan

在片段外部的类中调用getViewById会生成空指针异常,并且

  •  -1
  • Rares Stan  · 技术社区  · 7 年前

    我正试着把文本从 TextView 那是在 Fragment 什么时候 onLocationChanged 函数被调用。

    我知道我可以实施 LocationListener 创建时 HomeFragment 但我希望这是模块化的。

    public void onLocationChanged(Location location) {
    
        Log.i(TAG,"onLocationChanged method called");
    
        HomeFragment hf = new HomeFragment();
    
        if(hf == null)
        {
            Log.i(TAG,"hf is null");
        }
        else {
            if(hf.getView().findViewById(R.id.speed_box) == null)
            {
                Log.i(TAG,"findViewById failed");
            }
            else {
                TextView speedBox = (TextView) hf.getView().findViewById(R.id.speed_box);
    
                if (location == null) {
                    if (speedBox != null) {
                        speedBox.setText("unknown m/s");
                    } else {
                        Log.i(TAG, "speedBox object is null");
                    }
                } else {
                    Log.i(TAG, "onLocationChanged method called, the speed is: " + location.getSpeed());
                    float speed = location.getSpeed();
    
                    if (speedBox != null) {
                        speedBox.setText(location.getSpeed() + " m/s");
                    }
                    {
                        Log.i(TAG, "speedBox object is null");
                    }
                }
            }
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Tam Huynh    7 年前

    创建一个 HomeFragment ,但它尚未附加到布局,这就是为什么 null 从…起 getView

    片段需要通过来自的事务附加到活动 FragmentManager 然后 fragment.onCreateView 被称为 获取视图 不会返回null。

    对我来说,你不想使用listener的原因并不是它应该是什么。在位置感知应用程序中,位置回调应该是全局的,任何需要侦听位置更改的组件都可以在任何地方注册侦听器。

    以下是我将如何实施它:

    • 有一个单身汉 AppLocationManager 类保存位置逻辑,如果位置发生更改,它将向所有侦听器保留LocationListener和fire事件的列表。 AppLocationManager 不需要知道它的依赖关系或它们是什么,它只做一项工作。
    • 家庭片段 将侦听器注册到 AppLocationManager 在里面 onCreateView ,侦听更改并更新其文本视图。
    • 任何其他组件都可以将侦听器注册到 AppLocationManager 如果他们想 家庭片段
        2
  •  0
  •   jantursky    7 年前

    首先,您可能不希望每次 碎片类 ,而不是那样,您应该只实例化这个类一次,并检查这个片段的可访问性,因此有几个选项:

    1. option—在这种情况下,只实例化一次片段类,并将此方法用作变量保持器

      private HomeFragment hf; 
      
      public Fragment getHomeFragment() {
          if (hf == null) {
              hf = new HomeFragment();
          }
          return hf; 
      }
      
    2. 查找已可见的片段:

      Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);
      if (currentFragment != null) {
          if (currentFragment instanceof HomeFragment) {
              //do your action
          }
      }
      

    至少,试着发布整个类,在那里你有你的onLocationChanged方法