ViewPager找不到片段id的视图

时间:2014-02-06 08:45:09

标签: android android-fragments

我有一个视图寻呼机,它有一个由FragmentActivity托管的3个标签片段。

我要做的是在点击项目后用新的片段替换这些片段:

public class UserShopActivity extends FragmentActivity implements
        UserItemsFragment.OnUserItemSelectedListener,
        UserCategoriesFragment.OnUserCategoriesSelectedListener,
        UserSelectedCategoryFragment.OnUserItemsSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_user_profile);

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.shop_pager);
        setContentView(mViewPager);
}

 ...

    @Override
    public void onUserCategoriesSelected(String category_id) {
        UserSelectedCategoryFragment fragment = new UserSelectedCategoryFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.shop_container, fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .addToBackStack(null)
                .commit();
}
}

但是我收到了这个错误:

  

java.lang.IllegalArgumentException:找不到id 0x7f070011的视图   (com.ked.ai:id/shop_container)片段   UserSelectedCategoryFragment {40f7bcf0#3 id = 0x7f070011}

我已经在setContentView的viewpager中设置了一个容器ID,即shop_container

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shop_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/shop_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.v4.view.ViewPager>

但它找不到身份证。如何正确更换?

1 个答案:

答案 0 :(得分:1)

您不需要在ViewPager中替换需要实现FragmentPagerAdapterFragmentStatePagerAdapter的片段,以便在视图寻呼机中显示片段。

欲了解更多信息:

http://developer.android.com/training/animation/screen-slide.html

尝试更改为:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/shop_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

<android.support.v4.view.ViewPager 
    android:id="@+id/shop_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >




</android.support.v4.view.ViewPager>
</FrameLayout>

onCreate更改为:

public class UserShopActivity extends FragmentActivity implements
        UserItemsFragment.OnUserItemSelectedListener,
        UserCategoriesFragment.OnUserCategoriesSelectedListener,
        UserSelectedCategoryFragment.OnUserItemsSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_user_profile);
        setContentView(R.layout.yourlayoutname);
        mViewPager = (ViewPager)findViewById(R.id.shop_pager);


}