私はMainActivity
を使用してviewPager
を使用し、ユーザーのスワイプジェスチャーについて2つのfragment
ビューをインスタンス化します。フラグメントの1つがサーバーからデータを取得し、そのビューを更新します。ViewPager:ユーザーのスワイプでフラグメントビューを更新する
問題:なしインターネット接続でアプリを起動する
、いくつかのダミーデータとfragment
Aの更新が、その後、アプリが起動して、そのフラグメントにスワイプしている間のWi-Fiの切り替え時に更新されません。受信したデータとの断片。
fragment
ビューは、インスタンス化された後に更新することができます。次のように
MainActivity.java
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragment1.newInstance();
case 1:
return fragment3.newInstance();
default:
return fragment1.newInstance();
}
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
FragmentAクラス(コードでFragment3)が与えられる。
public class fragment3 extends Fragment implements YourFragmentInterface{
public static ListView mylistView;
public static ConfessionsAdapter adapter;
public static ArrayList<Confession> confessionList;
public static Context context;
public static fragment3 newInstance() {
fragment3 fragment = new fragment3();
new HttpGetReq().execute("http://example.com");
return fragment;
}
public fragment3() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = getActivity(); // Getting context to tell async task about it, so it can SET stuff here.
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.list_fragment, container, false);
mylistView = (ListView) view.findViewById(android.R.id.list);
new HttpGetReq().execute("http://example.com");
return view;
}
}
HttpGetReq
クラスは、サーバーからデータを取得すること、AsyncTask
でJSONを解析しますメソッド内のフラグメントAのlist
を更新し、アダプタをonPostExecute()
メソッドのフラグメントAのリストView
に設定します。