Android TabLayout 使用

本文介绍如何使用TabLayout和ViewPager组件实现固定的标签导航栏,并通过示例代码展示如何设置TabLayout的各种属性,如颜色、模式等,同时展示了如何将TabLayout与ViewPager结合使用来实现动态切换内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

依赖 
compile 'com.android.support:design:25.3.1'

TabLayout属性

app:tabMode="fixed"         固定
app:tabMode="scrollable"    可滑动
app:tabIndicatorColor       滚动下划线的颜色  
app:tabSelectedTextColor    tab选中后文字的颜色  
app:tabTextColor            tab默认显示的文字颜色  
app:tabMaxWidth             tab最大宽度
app:tabMinWidth             tab最小宽度

设置tabMode为 scrollable

<android.support.design.widget.TabLayout
     android:layout_width="match_parent"
     android:layout_height="48dp"
     app:tabMode="scrollable"
     app:tabIndicatorColor="#ff00ff"
     app:tabTextColor="#000000"
     app:tabSelectedTextColor="#ff0000"
     >

添加tab标题

TabLayout mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
mTabLayout.addTab(mTabLayout.newTab().setText("tab_1"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_2"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_3"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_4"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_5"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_6"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_7"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_8"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_9"));
mTabLayout.addTab(mTabLayout.newTab().setText("tab_10"));

运行后效果如下:
scrollable.gif

修改tabMode为 fixed重新运行

app:tabMode="fixed"

发现页面无法滑动。
fixed.gif

通常TabLayout和ViewPager配合在一起使用,先看图:

home.gif

布局代码:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
  >
    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:tabMode="fixed"
        app:tabIndicatorColor="#ff00ff"
        app:tabTextColor="#000000"
        app:tabSelectedTextColor="#ff0000"
        >

    </android.support.design.widget.TabLayout>


    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</LinearLayout>

创建layout_home,layout_address,layout_discover,layout_me布局
布局都一样,只有一个TextView,分别为首页,通讯录,发现,我。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="首页"
        />
</LinearLayout>

Activity 中代码

public class TabLayoutActivity extends AppCompatActivity {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List<View> mViewList;
    private List<String> mTitleList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);

        mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        View home = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_home, null);
        View address = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_address, null);
        View discover = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_discover, null);
        View me = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_me, null);

        mViewList = new ArrayList<>();
        mViewList.add(home);
        mViewList.add(address);
        mViewList.add(discover);
        mViewList.add(me);

        mTitleList = new ArrayList<>();
        mTitleList.add("首页");
        mTitleList.add("通讯录");
        mTitleList.add("发现");
        mTitleList.add("我");

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return mViewList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mViewList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(mViewList.get(position));
                return mViewList.get(position);
            }

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

        mTabLayout.setupWithViewPager(mViewPager);

        //TabLayout监听
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //切换tab时不使用ViewPager动画效果
                mViewPager.setCurrentItem(tab.getPosition(),false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}
运行即可实现图中的效果。
### 如何在Android使用TabLayout #### 添加依赖项 为了能够在项目中使用`TabLayout`组件,需要先配置项目的构建文件。具体来说,在`build.gradle`文件中的dependencies部分添加如下内容: ```gradle dependencies { implementation 'com.google.android.material:material:1.6.0' } ``` 这一步骤确保了可以访问最新的Material Design库,其中包含了`TabLayout`控件[^4]。 #### 创建布局文件 接着定义XML布局文件来放置`TabLayout`和其他视图组件。通常会将`TabLayout`与`ViewPager2`一起使用以便更好地管理页面切换效果。下面是一个简单的例子: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout> ``` 此布局设置了垂直方向上的线性排列,并且让`ViewPager2`占据剩余的空间[^3]。 #### 初始化并设置Tabs 在Activity或Fragment类里初始化这些UI元素,并建立它们之间的关联关系。这里展示了一个基本的方式去创建几个标签页并将它们绑定到适配器上: ```java import com.google.android.material.tabs.TabLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager2.adapter.FragmentStateAdapter; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabLayout tabLayout = findViewById(R.id.tab_layout); ViewPager2 viewPager = findViewById(R.id.view_pager); MyPagerAdapter adapter = new MyPagerAdapter(this); viewPager.setAdapter(adapter); // 将TabLayout和ViewPager连接起来 new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText("TAB " + (position + 1)) ).attach(); // 设置分隔符样式 LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0); linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_vertical)); } private static class MyPagerAdapter extends FragmentStateAdapter { public MyPagerAdapter(@NonNull FragmentActivity fragmentActivity) { super(fragmentActivity); } @NonNull @Override public Fragment createFragment(int position) { return PlaceholderFragment.newInstance(position + 1); } @Override public int getItemCount() { return 3; // 或者其他数量的tabs } } } ``` 上述代码片段展示了如何动态地向`TabLayout`添加多个标签以及自定义其外观,比如通过调用`setShowDividers()`方法为相邻的两个标签间增加一条细线作为视觉区分[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值