基本上我有我的片段
public class FragmentDashboard extends Fragment {
public static FragmentDashboard newInstance() {
FragmentDashboard frag = new FragmentDashboard();
return frag;
}
public void updateData(Object object){
myTextView.setText(object.getField);
//update views with object values
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
myTextView = (TextView) view.findViewById(R.id.myTextView );
}
}
然后在我的活动中,我需要更新我所做的数据:
FragmentDashboard fragmentDashboard = (FragmentDashboard) getSupportFragmentManager().findFragmentById(R.id.layFragment);
fragmentDashboard.updateData(myObject)
如果我在显示 Fragment 之后调用我的活动(例如从完成的异步任务),这会很好。
我遇到的问题是在我将片段添加到我的活动的 onCreate() 之后必须立即运行 updateData。
final FragmentTransaction ft = fragmentManager.beginTransaction();
FragmentDashboard fragmentDashboard = FragmentDashboard.newInstance();
ft.replace(R.id.layFragment, fragmentDashboard);
ft.commit();
fragmentDashboard.updateData(myObject)
运行这个我得到一个 NPE,因为片段onCreateView
尚未运行并且myTextView
尚未初始化
我不想在 newInstance 上添加参数,因为我想避免使对象成为可打包的。有任何想法吗 ?