【发布时间】:2014-01-20 07:43:02
【问题描述】:
亲爱的,
我搜索这个问题超过一天,但没有运气。 我完全实现了这里发布的代码:
我的 onTabSelected 代码如下所示:
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(R.id.alert_fragment_container, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
// prepare adapter for ExpandableListView
Log.i("After Adapter Created", "Passed");
final ExpandableListAdapter expListAdapter = new AlertsAdapter(
mActivity, myAlerts, violations);
Log.i("After Adapter Initialized", "Passed");
((MyCustomFragment)mFragment).violations.setAdapter(expListAdapter);
}
代码运行良好,直到最后一行,我需要在onCreateView 中为在MyCustomFragment 中初始化的公共静态列表设置适配器,这是我的片段代码:
public class MyCustomFragment extends Fragment {
public MyCustomFragment() {
}
public static ExpandableListView violations;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_alerts_poi, container, false);
violations = (ExpandableListView) rootView.findViewById(R.id.POIAlertList);
Log.i("onCreateView POI", "Called");
return rootView;
}
}
它给出空指针错误。通过我的调试日志,我注意到这个日志Log.i("onCreateView POI", "Called"); 出现在这个Log.i("After Adapter Initialized", "Passed"); 之后。这意味着我正在尝试为尚未初始化的片段设置适配器。
这正是我面临的问题,我需要根据onTabSelected 中的选项卡选择向ExpandableListView 提供数据。
我做错了什么?什么是最好的解决方案?
问候,
【问题讨论】:
-
“亲爱的”? +1 以防万一您是编程祖母
-
看看@这个Tablayout.OnTabSelectedListener以获取最新更新。