我正在跟进android viewpager tutorial,我收到了此错误
java.lang.NullPointerException:尝试调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'为null 对象参考
我知道它说我设置空值但我的qeustion为什么它为空?我正在返回值
public class SingleViewActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
DemoCollectionPagerAdapter
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
/* if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
MyFragment myrag = new MyFragment();
myrag.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, myrag).commit();
}
*/
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 100;
}
@Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
}
答案 0 :(得分:1)
您必须先使用[alias]
hist = log --pretty=format:\"%C(yellow)%h [%ad]%C(reset) | %s%d %C(green)(%cr)%C(reset) by %C(blue)%an%C(reset)\" --graph --all --decorate --date=short
获取对TextView的引用,然后才能在其上调用View.findViewById(R.id.the_id_of_the_view)
。
注意:我在findViewById()方法中删除了'android'。
答案 1 :(得分:1)
更改
((TextView) rootView.findViewById(android.R.id.text1)).setText(...)
到
((TextView) rootView.findViewById(R.id.text1)).setText(...)
其中@+id/text1
是您的textview的ID。