1. 程式人生 > >TabLayout 使用方法 (基礎)

TabLayout 使用方法 (基礎)

ted ima break hit widget 監聽 pri cti idt

  • 此為布局文件

<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 !

TabLayout 使用方法 (基礎)