尝试将 ViewPager 与 FragmentPagerAdapter 与所有动态 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;
}
}
似乎是如何/何时创建片段的问题,但未能找到连接......