我的目标是在主要活动中初始化视图,但我得到了 nullpointerexception。这是我的示例代码:
public class MainActivity extends SherlockFragmentActivity {
private static final String TAG = "MainActivity";
Fragment one, two, three;
List<Fragment> fragments;
ViewPager pager;
private MyPagerAdapter mPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialisePaging();
initTwo ();
}
private void initialisePaging() {
Log.d(TAG, "initialisePaging");
fragments = new Vector<Fragment>();
one = Fragment.instantiate(getApplicationContext(), One.class.getName());
two = Fragment.instantiate(getApplicationContext(), Two.class.getName());
three = Fragment.instantiate(getApplicationContext(), Three.class.getName());
fragments.add(one);
fragments.add(two);
fragments.add(three);
mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragments) ;
pager = (ViewPager) findViewById(R.id.trinity_viewpager);
pager.setAdapter(mPagerAdapter);
}
private void initTwo (){
View twoView = mPagerAdapter.getItem(1).getView();
TextView twoTv = (TextView) twoView.findViewById(R.id.frag_two_tv);
twoTv.setText("2!!!!");
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return 3;
}
}
}
片段一、二和三仅包含 textView。我尝试初始化这些视图并得到 NullPointerException:
E/AndroidRuntime(2104): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2104): at ru.alxr.viewpagerapp.MainActivity.initTwo(MainActivity.java:53)
E/AndroidRuntime(2104): at ru.alxr.viewpagerapp.MainActivity.onCreate(MainActivity.java:34)
E/AndroidRuntime(2104): at android.app.Activity.performCreate(Activity.java:5008)
E/AndroidRuntime(2104): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
E/AndroidRuntime(2104): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)