我有我的MainActivity
使用viewPager
並實例化兩個用戶輕掃手勢的fragment
視圖。其中一個片段從服務器獲取一些數據並更新其視圖。ViewPager:刷新用戶划動的片段視圖
問題:
開始,沒有互聯網連接的應用程序,fragment
一些虛擬數據,但隨後在當應用程序正在運行,然後滑動到該片段不更新切換無線網絡連接更新片段與收到的數據。
請建議如何在實例化後更新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並在doInBackground()
方法中更新片段A的list
,然後在其onPostExecute()
方法中將適配器設置爲片段A的列表View
。