1

基本上我有我的片段

        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 上添加参数,因为我想避免使对象成为可打包的。有任何想法吗 ?

4

2 回答 2

1

您可以使用本地字段来包含您的数据并在您的onCreateView方法中使用它:

public class FragmentDashboard extends Fragment {

    private Object myData=null;
    private TextView myTextView = null;

    public static FragmentDashboard newInstance() {
        FragmentDashboard frag = new FragmentDashboard();
        return frag;
    }

   public void updateData(Object object){
       myData = object;
       if(myTextView != null)
           myTextView.setText(myData);
   }

   @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 );
       if(myData != null && myTextView != null)
           myTextView.setText(myData);
   }
}
于 2013-08-20T11:50:57.827 回答
1

将 Data 设置为 updateData(Object ) 不是一个好习惯。使您的模型类可打包或可序列化,并将其传递到 putExtra 并在 onViewCreated 中获取。

    public static FragmentDashboard newInstance(Object object) {
                Bundle args = new Bundle();
                args.putParcelable("yourModelClass",object);
                FragmentDashboard frag = new FragmentDashboard();
                frag.setArguments(args);
                return frag;
     }    

并在onViewCreated

if(getArguments != null)
    yourModelClassObject = getArguments().getParcelable("yourModelClass");

 if(yourModelClassObject != null)
     textView.setText(yourModelClassObject.getField());

我已经口头写过代码。可能包含错误。

于 2017-01-27T06:34:28.540 回答