使用viewpager's addOnPageChangeListener
事件是這樣的:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(position == 1){
//call your webservice here
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
注意,頁面位置從0開始讓你的第二個標籤位置是1
編輯:如何獲得當前片段的實例
Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof SecondFragmentClass) {
f.doSomething();
}
注意:如果您已提供標籤
,您可以使用findFragmentByTag()代替findFragmentById
更新:
if(position == 1){
Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem());
// based on the current position you can then cast the page to the correct
// class and call the method:
if (page != null) {
((SecondFragmentClass)page).updateList("new item");
}
return true;
}
檢查這個答案更好understandig https://stackoverflow.com/a/18611036/5895830
我怎樣才能把當前片段的實例是指執行任務的第二個片段? – vaibhav
檢查我更新的答案 –