gpt4 book ai didi

android - 在 newInstance() 之后更新 fragment 数据

转载 作者:行者123 更新时间:2023-11-29 21:36:20 24 4
gpt4 key购买 nike

基本上我有我的 fragment

        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 );
}
}

然后在我的 Activity 中我需要更新我所做的数据:

FragmentDashboard fragmentDashboard = (FragmentDashboard) getSupportFragmentManager().findFragmentById(R.id.layFragment);
fragmentDashboard.updateData(myObject)

如果我在 Fragment 显示后调用我的 Activity(例如从完成的异步任务),这会很好用。

我遇到的问题是必须在我将 fragment 添加到 Activity 的 onCreate() 后立即运行 updateData。

final FragmentTransaction ft = fragmentManager.beginTransaction();

FragmentDashboard fragmentDashboard = FragmentDashboard.newInstance();
ft.replace(R.id.layFragment, fragmentDashboard);
ft.commit();

fragmentDashboard.updateData(myObject)

运行这个我得到一个 NPE 因为 fragment 的 onCreateView 还没有运行并且 myTextView 没有初始化

我不想在 newInstance 上添加参数,因为我想避免使对象成为可打包的。有什么想法吗?

最佳答案

您可以使用本地字段来包含您的数据并在您的 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);
}
}

关于android - 在 newInstance() 之后更新 fragment 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18334063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com