0
爲了關注這個問題,我結束了以下測試應用程序,其中包含一個活動和兩個連接到FragmentStatePagerAdapter/ViewPager的片段。我也每秒都有Runnable和Handler打印getView()(在生產版本中,它用於在片段的TextView中顯示時間)。片段getView在掛起後爲null
當我啓動應用程序,getView()表示,也許幾個空(我想,由於片段生命週期),然後我得到一些非空值這是確定...
但是,如果我暫停和喚醒我設備LogCat始終顯示空值。
public class MainActivity extends SherlockFragmentActivity {
private SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
private Fragment myFragment1 = new MyFragment1();
private Fragment myFragment2 = new MyFragment2();
private Handler handler = new Handler();
private Runnable timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(sectionsPagerAdapter);
}
@Override
protected void onResume() {
super.onResume();
timer = new Runnable() {
public void run() {
System.out.println(myFragment1.getView()); // HERE getView gives null
handler.postDelayed(this, 1000); // refreshing every 1 sec
}
};
handler.removeCallbacks(timer);
handler.postDelayed(timer, 0);
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(timer);
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 0) {
fragment = myFragment1;
} else {
fragment = myFragment2;
}
return fragment;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Fragment 1";
case 1:
return "Fragment 2";
}
return null;
}
}
}
我的片段
public class MyFragment1 extends SherlockFragment {
private TextView textView2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_layout, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((TextView) getView().findViewById(R.id.textView1)).setText("Fragment 1");
textView2 = (TextView) this.getView().findViewById(R.id.textView2);
}
public void updateTextView2(String text) {
textView2.setText(text);
}