下面我将详细介绍“Android基于API的Tabs3实现仿优酷tabhost效果实例”的完整攻略,包括具体的实现过程和两个示例说明。
实现仿优酷tabhost效果的方案主要涉及两个部分:一是使用API实现Tabs3页面,二是为每个页面添加Fragment布局。
具体步骤:
下面我将给出两个示例,一个是实现简单的Tab页面,一个是带有动态切换内容的Tab页面。
在布局文件中添加ViewPager和TabLayout控件,为Fragment添加对应的布局文件。
布局文件:
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:tabIndicatorColor="@color/colorAccent"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/white" />
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
创建Fragment:
public class HomeFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
}
创建FragmentAdapter并为其添加Fragment:
public class FragmentAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
在TabLayout中设置TabItem:
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Settings"));
绑定ViewPager与TabLayout:
ViewPager viewPager = findViewById(R.id.viewPager);
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment(), "Home");
adapter.addFragment(new SettingsFragment(), "Settings");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
通过点击TabLayout内的Item,显示对应的Fragment页面。
实现步骤:
代码实现:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
switch (position) {
case 0:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
break;
case 1:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutFragment()).commit();
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
以上就是Android基于API的Tabs3实现仿优酷tabhost效果实例的完整攻略和两个示例说明。