newInstance()后更新片段数据

时间:2013-08-20 11:39:52

标签: android android-fragments

基本上我有我的片段

        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)

如果我在显示片段后对我的活动进行调用(例如从已完成的asynctask开始),那么这很有效。

我遇到的问题是我在活动的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上添加参数,因为我想避免将对象设为parcelable。有什么想法吗?

2 个答案:

答案 0 :(得分: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);
   }
}

答案 1 :(得分:1)

  

将数据设置为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());
  

我口头写了代码。可能包含错误。