視圖尋呼機片段始終加載其鄰居在任何一方。
正因爲如此,您將看到碎片在可見之前運行的創建回調。離開一個碎片2頁後,它將被銷燬。
讓您的活動執行ViewPager.OnPageChangeListener
然後使用onPageSelected
將呼叫轉入您的片段。您可以在該活動中保留對視圖頁片段的引用。
public class ViewPagerActivity implements ViewPager.OnPageChangeListener {
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
...
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}
// regular activity stuff plus view pager methods
@Override
public void onPageSelected(int arg0) {
final ReadyFragment fragment = mAdapter.getItem(arg0);
if (fragment.isVisible()) {
fragment.ready(); //method inside your custom fragment code
}
}
}
添加一個接口類:
public interface ReadyInterface {
public void ready();
}
實現該接口在您的片段:
public class ReadyFragment extends Fragment implements ReadyInterface {
//.. your regular fragment stuff
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's state here
}
@Overide
public void ready() {
// do your stuff here that needs to happen
//once fragment is displayed and running
}
}
Pager適配器的'getItem'方法是否創建片段的新實例? –
它什麼都不做 – kerollos
你什麼意思不做什麼?它必須返回一個視圖或片段(可能是您的案例中的片段)。 –