(四)——APP主页框架TabHost绑定ViewPager的替换者TabLayout

最后更新于:2022-04-01 09:36:14

# Android特效专辑(四)——APP主页框架TabHost绑定ViewPager的替换者TabLayout > 现在很多app都在追求简单明了,功能又要强大,不过我还是喜欢之前的app风格,就是TabHost,在现在也是有许多app在用,不过选项卡可能都放在下面了,我们想要tabhost有viewpager的滑动效果,其实也很简单,那就是fragment,在这之前,我都是很复杂的把它们全部绑定在一起联动的,但是现在就要简单很多了 ,我们用Android Studio开发 先看下效果图吧 ![这里写图片描述](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-02-24_56cd2c17315a0.jpg "") ~~~ 我们这次使用到的是TabLayout ~~~ ### activity_main.xml ~~~ <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/id_tab_layout" android:background="#ffffff" app:tabGravity="fill" app:tabMode="fixed" app:tabIndicatorColor="#0ddcff" app:tabTextColor="#000000" app:tabSelectedTextColor="#0ddcff" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/id_view_pager" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v4.view.ViewPager> </LinearLayout> ~~~ ### MainActivity ~~~ package com.app.gaohailong.festivalmessage; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private TabLayout mTablayout; private ViewPager mViewPager; private String[] mTitles = new String[]{"节日短信", "发送记录", "个人设置"}; private List<Fragment> mFragments; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); } private void initViews() { //初始化View mTablayout = (TabLayout) findViewById(R.id.id_tab_layout); mViewPager = (ViewPager) findViewById(R.id.id_view_pager); //初始化List<Fragment> mFragments = new ArrayList<>(); Fragment mFestivalFragment = new FestivalFragment(); Fragment mRecordFragment = new RecordFragment(); Fragment myFragment = new MyFragment(); mFragments.add(mFestivalFragment); mFragments.add(mRecordFragment); mFragments.add(myFragment); //给ViewPage设置Adapter mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mTitles[position]; } }); mTablayout.setupWithViewPager(mViewPager); } } ~~~ ~~~ 记得添加源 ~~~ ~~~ compile 'com.android.support:design:23.1.1' ~~~ ~~~ 这样就可以了,是不是非常的简单?你也可以去试试呢 ~~~
';