在android studio中的选项卡中的选项卡

时间:2016-08-20 11:16:56

标签: android android-fragments android-viewpager android-tabhost

我只想在Tabs中实现Tabs。如果有可能请分享代码

见下图以供参考

enter image description here

1 个答案:

答案 0 :(得分:1)

这是我的问题的答案。我在选项卡中设置选项卡。基本上在片段中设置选项卡:

我的java代码:

public class SD extends Fragment {
View view;
PagerAdapter adapter;
public SD() {
    // Required empty public constructor
}

private void setupViewPager(ViewPager viewPager) {

///这里我们必须传递ChildFragmentManager而不是FragmentManager。

    adapter = new PagerAdapter(getChildFragmentManager());
    adapter.addFragment(new Sim1Detail(), "Sim 1");
    adapter.addFragment(new Sim2Detail(), "Sim 2");
    viewPager.setAdapter(adapter);
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.sd, container, false);
    super.onCreate(savedInstanceState);
   // ButterKnife.bind(getActivity(), view);
    final ViewPager viewPager = ButterKnife.findById(view, R.id.viewpager);
    setupViewPager(viewPager);
    TabLayout tabLayout = ButterKnife.findById(view, R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    return view;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
   // ButterKnife.unbind(getActivity);
}

static class PagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragments = new ArrayList<>();
    private final List<String> mFragmentTitles = new ArrayList<>();

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


    public void addFragment(Fragment fragment, String title) {
        mFragments.add(fragment);
        mFragmentTitles.add(title);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitles.get(position);
    }
}

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabMode="fixed" />

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

这里是..