Fist off,我需要初始化一系列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);
所以我怎样才能在加载NetWork数据后立即更新Fragment中的数据。
答案 0 :(得分:4)
一旦网络请求完成并且活动完成处理数据,它就可以使用interface
将其传递给片段。
的活动:
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);
}
}
片段:
public class MyFragment extends Fragment implements onDataLoadedListener
{
@Override
public void onDataLoaded(receivedData)
{
// Handle the received data accordingly
}
}