gpt4 book ai didi

android - Activity加载完数据后如何将数据从Activity设置到Fragment

转载 作者:行者123 更新时间:2023-11-29 17:19:52 27 4
gpt4 key购买 nike

开始吧,我需要初始化一系列 fragment 类;之后,我做了一些网络请求;加载完所有数据后,我需要将我指定的数据从 Activity 传输到 Fragment,但我不知道这个过程。

代码如下:

    private Class[] mFragmentClasses = {GoodDetailsFragment.class,GoodDetailsArgumentsFragment.class};
mIndicator.setViewPager(mViewPager);
mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

@Override
public int getCount() {
return mFragmentClasses.length;
}

@Override
public Fragment getItem(int position) {
try {
return (Fragment) mFragmentClasses[position].newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
};
mViewPager.setAdapter(mAdapter);

那么我如何在加载网络数据后立即更新来自 Fragment 的数据。

最佳答案

一旦网络请求完成并且 Activity 处理完数据,它就可以使用接口(interface)将其传递给 fragment 。

Activity :

public class MainActivity extends Activity
{
public interface onDataLoadedListener
{
public void onDataLoaded(String receivedData);
}

onDataLoadedListener onDataLoadedListener;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Fragment fragment = new MyFragment();
onDataLoadedListener = fragment;
}

// Some method called when you receive the data
public void onDataReceived(String receivedData)
{
onDataLoadedListener.onDataLoaded(receivedData);
}
}

fragment :

public class MyFragment extends Fragment implements onDataLoadedListener
{
@Override
public void onDataLoaded(receivedData)
{
// Handle the received data accordingly
}
}

关于android - Activity加载完数据后如何将数据从Activity设置到Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084128/

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