Android 在片段外部的类中调用getViewById会生成空指针异常和
当调用Android 在片段外部的类中调用getViewById会生成空指针异常和,android,nullpointerexception,location,fragment,getview,Android,Nullpointerexception,Location,Fragment,Getview,当调用onLocationChanged函数时,我试图更改TextView中片段中的文本 我知道我可以在创建HomeFragment时实现LocationListener,但我希望这是模块化的 public void onLocationChanged(Location location) { Log.i(TAG,"onLocationChanged method called"); HomeFragment hf = new HomeFragment(); if(
onLocationChanged
函数时,我试图更改TextView
中片段中的文本
我知道我可以在创建HomeFragment
时实现LocationListener
,但我希望这是模块化的
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");
}
}
}
}
}
首先,您可能不想每次初始化片段类,相反,您应该只实例化一次该类并检查该片段的可访问性,因此有几个选项:
选项-在这种情况下,只实例化一次片段类,并将此方法用作变量持有者
private HomeFragment hf;
public Fragment getHomeFragment() {
if (hf == null) {
hf = new HomeFragment();
}
return hf;
}
查找已可见的片段:
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);
if (currentFragment != null) {
if (currentFragment instanceof HomeFragment) {
//do your action
}
}
至少,试着发布整个类,在那里你有你的onLocationChanged方法你创建了一个HomeFragment
的实例,但是它还没有附加到布局,这就是为什么你从getView
得到null
片段需要通过来自FragmentManager
的事务附加到活动,然后fragment。一旦调用CreateView
,则getView
将不会返回null
对我来说,你不想使用listener的原因不是它应该是什么。在位置感知应用程序中,位置回调应该是全局的,任何需要侦听位置更改的组件都可以在任何地方注册侦听器
以下是我将如何实施它:
- 有一个保存位置逻辑的singleton
AppLocationManager
类,如果位置发生更改,它会将LocationListener和fire事件的列表保留给所有侦听器AppLocationManager
不需要知道它的依赖项或它们是什么,它只做一项工作
HomeFragment
将侦听器注册到onCreateView
中的AppLocationManager
,侦听更改并更新其文本视图
- 任何其他组件都可以将侦听器注册到
AppLocationManager
,只要它们愿意,就像HomeFragment
一样