我正在尝试整理一个简单的视图寻呼机应用,我希望将其延伸到后面。
目前,当我在ViewPager vPager = (ViewPager) findViewById(R.id.viewPager);
的{{1}}方法中调用onCreate
时,它会返回null。
以下是完整的解释:
我的GUI xml看起来像这样:
FragmentActivity
相应的Fragment类如下所示:
\res\layout\view_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
我有一个像这样的寻呼机xml:
public class ViewFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.view_fragment, container, false);
}
}
我的Pager Activity看起来像这样:
\res\layout\view_pager.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
但是,语句public class ScreenPagerActivity extends FragmentActivity {
private ViewPager vPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_fragment); // The view
vPager = (ViewPager) findViewById(R.id.viewPager);
ScreenPagerAdapter pagerAdapter = new ScreenPagerAdapter(getSupportFragmentManager());
vPager.setAdapter(pagerAdapter);
}
@Override
public void onBackPressed() {
if (vPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
vPager.setCurrentItem(vPager.getCurrentItem() - 1);
}
}
private class ScreenPagerAdapter extends FragmentStatePagerAdapter {
public ScreenPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return new ViewFragment();
}
@Override
public int getCount() {
return 5;
}
}
}
始终返回null。谁能告诉我哪里出错了。
只是为了帮助,我的活动代码段的Manifest文件如下所示:
vPager = (ViewPager) findViewById(R.id.viewPager);
请帮助!!!
由于
答案 0 :(得分:5)
我认为你选择了错误的观点。试试这个:
setContentView(R.layout.view_pager); // The view where your ViewPager is!
而不是
setContentView(R.layout.view_fragment); // The view for your Fragment.
这就是你的ViewPager返回null的原因,因为该方法无法在选择的布局中找到它 HTH