TabLayout 使用方法 (基础)

  • 此为布局文件

<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.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/white"
        app:title="TabLayout使用" >
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

</LinearLayout>
  • 使用之添加 Tab
//引入布局
mTabLayout = (TabLayout) findViewById(R.id.tab_layout2);
mTabLayout.addTab(mTabLayout.newTab().setText(
"Item1")); mTabLayout.addTab(mTabLayout.newTab().setText("Item2"));
mTabLayout.addTab(mTabLayout.newTab().setText("Item3"));
  • 添加监听
 mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                switch (tab.getPosition()) {
                    case 0:
                        Toast.makeText(youhuiActivity.this, "Test1", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(youhuiActivity.this, "Test2", Toast.LENGTH_SHORT).show();
                        break;
                }

            }

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

            }

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

            }
        });
    }

成功使用简易 TabLayout !

原文地址:https://www.cnblogs.com/douzujun/p/7173926.html