在片段中添加Viewpager

时间:2016-05-20 12:11:09

标签: android-layout android-fragments android-studio fragment

您好我使用片段创建了我的应用程序,我需要在其中一个中实现viewpager(在viewpager用户可以在不同信息之间滑动(关于使用我当前正在开发的应用程序)。我假设将有3到5个视图,包含文本和详细信息))。贝娄是当前片段的代码。你能不能让我知道在片段中实现Viewpager的最佳方式是什么?让我们说3个视图,每个视图都会有3或4个东西(Imageview,Textview等)。我已经在其他活动中实现了Viewpager,但这是我第一次在片段中实现它。它的逻辑是什么?我尝试使用谷歌,但听起来很复杂。

public class AboutSectionFragment extends Fragment   {


    // The onCreateView method is called when Fragment should create its View object hierarchy,
    // either dynamically or via XML layout inflation.
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.about_section, parent, false);

        // Defines the xml file for the fragment
        return rootView ;
    }

    // This event is triggered soon after onCreateView().
    // Any view setup should occur here.  E.g., view lookups and attaching view listeners.
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

    }
    }

1 个答案:

答案 0 :(得分:0)

我在片段中使用了ViewPager,它对我来说很好。

片段类

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_content, container, false);
        fragments = getFragmentsList();
        pagerAdapter = new HomeViewPagerAdapter(getChildFragmentManager(),fragments);
        ViewPager = (ViewPager) view.findViewById(R.id.Home_View_Pager);
        ViewPager.setAdapter(pagerAdapter);

 private ArrayList<Fragment> getFragmentsList(){
    fragments = new ArrayList<>();
    fragments.add(HomeViewPagerFragment.getInstance());
    fragments.add(HomeViewPagerFragment.getInstance());
    fragments.add(HomeViewPagerFragment.getInstance());
    fragments.add(HomeViewPagerFragment.getInstance());
    fragments.add(HomeViewPagerFragment.getInstance());

    return fragments;
}

ViewPager Fragment Class

public class HomeViewPagerFragment extends Fragment {
    public static HomeViewPagerFragment getInstance(){
        HomeViewPagerFragment fragment = new HomeViewPagerFragment();
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_pager_fragment_layout,container,false);
        return view;
    }
}