我在使用 aViewPager
填充两个的活动时遇到问题Fragments
。在我的项目中,我有一个活动 RegisterActivity.java 和两个片段:FirstFragment.java 和 SecondFragment.java。创建活动时,会加载两个片段:
public class RegisterActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
EditText firstName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
firstName = (EditText) findViewById(R.id.edit_text_register_first_name);
firstName.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) { }
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// Do something...
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FirstFragment firstFragment = new FirstFragment();
return firstFragment;
case 1:
SecondFragment secondFragment = new SecondFragment();
return secondFragment;
}
return null;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
...
}
}
}
在 FirstFragment.java 中可以找到以下代码:
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View firstInterface = inflater.inflate(R.layout.fragment_first, container, false);
return firstInterface;
}
}
和 SecondFragment.java:
public class SecondFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View secondInterface = inflater.inflate(R.layout.fragment_second, container, false);
return secondInterface;
}
}
我可以向您保证,所有进口商品等都按要求提供。当我运行应用程序时,我NullPointerException
在第 41 行得到一个,这addTextChangedListener
是声明的地方。根据我所做的阅读,我猜测为什么会发生错误是因为edit_dext_register_first_name
它不是setContentView(R.layout.activity_register);
. 尽管它是其中一个片段布局的一部分,但应用程序不知道在哪里寻找 my EditText
,因此NullPointerException
. 不过我可能是错的。
我正在努力寻找如何解决这个问题,所以任何建议都将不胜感激。
谢谢!