当ViewGroup是动态的时,片段视图不会创建?

时间:2012-09-25 20:50:07

标签: android android-layout android-fragments

尝试将带有FragmentPagerAdapter的ViewPager与所有动态GUI元素(即没有XML)一起使用。是的,我有充分的理由,而不仅仅是因为我觉得它:)在文档中找不到任何表明这不起作用的内容。

工作和不工作之间的唯一区别是使用XML定义ViewGroup(LinearLayout)和ViewPager,而不是在onCreate()中创建。给出以下错误:

java.lang.IllegalArgumentException: No view found for id 0xffffffff for fragment PageFragment{41936480 #0 id=0xffffffff android:switcher:-1:0}

代码:

public class DynoPagerActivity extends FragmentActivity {

  private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {
        return PageFragment.newInstance("My Message " + index);
    }

    @Override
    public int getCount() {
        return 4;
    }
  }

  private ViewPager mViewPager;
  private MyFragmentPagerAdapter mMyFragmentPagerAdapter;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    setContentView(ll);

    mViewPager = new ViewPager(this);
    mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(mMyFragmentPagerAdapter);
    ll.addView(mViewPager);
    //setContentView(ll);  tried here as well...
  }
}

public class PageFragment extends Fragment {

public static PageFragment newInstance(String title) {

    PageFragment pageFragment = new PageFragment();
    Bundle bundle = new Bundle();
    bundle.putString("title", title);
    pageFragment.setArguments(bundle);
    return pageFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // https://android-review.googlesource.com/#/c/31261/  - bug in Support lib
    setUserVisibleHint(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    TextView textView = new TextView(container.getContext());
    textView.setText(getArguments().getString("title"));
    return textView;
}
}

似乎是关于如何/何时创建片段,但未能找到连接的问题......

1 个答案:

答案 0 :(得分:3)

ViewPager导致对每个“页面”调用findViewById(),该页面试图获取父(ViewPager ID),对于没有设置ID的视图,它总是失败。当您以编程方式创建视图时,它们获得的ID为-1,在浏览Android平台源代码后,始终为findViewByID()返回null / fail。

添加ID可以使其正常工作,但您需要自己安全地管理ID以避免出现问题。将其添加到上面的代码中,使其在onCreate()方法中起作用:

mViewPager.setId(888889);