1. 程式人生 > >TabLayout橫向標題

TabLayout橫向標題

需要匯入依賴:
compile ‘com.android.support:design:26+’

佈局:
<?xml version="1.0" encoding="utf-8"?>

		    <android.support.design.widget.TabLayout
		        android:id="@+id/tablayout"
		        android:layout_width="match_parent"
		        android:layout_height="wrap_content"></android.support.design.widget.TabLayout>
		
		    <android.support.v4.view.ViewPager
		        android:id="@+id/pager"
		        android:layout_width="match_parent"
		        android:layout_weight="1"
		        android:layout_height="0dp"/>

具體程式碼:
package gj.com.week3_1.frag;

		import android.os.Bundle;
		import android.support.annotation.NonNull;
		import android.support.annotation.Nullable;
		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.view.LayoutInflater;
		import android.view.View;
		import android.view.ViewGroup;
		
		import java.lang.reflect.Array;
		import java.util.ArrayList;
		
		import gj.com.week3_1.R;
		
		public class Frag01 extends Fragment {
		
		    private ViewPager pager;
		    private TabLayout tabLayout;
		    //建立大集合
		    ArrayList<String> titleList = new ArrayList<>();
		    ArrayList<Fragment> fragmentList = new ArrayList<>();//存放切換頁面的幀佈局
		
		    @Nullable
		    @Override
		    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		        View view = inflater.inflate(R.layout.frag01,container,false);
		        //初始化元件
		        pager = view.findViewById(R.id.pager);
		        tabLayout = view.findViewById(R.id.tablayout);
		        // 新增資料
		        for (int i = 0;i<3;i++){
		            titleList.add("標題"+(i+1));
		        }
		        //新增檢視
		        Frag_a frag_a = new Frag_a();
		        Frag_b frag_b = new Frag_b();
		        Frag_c frag_c = new Frag_c();
		        fragmentList.add(frag_a);
		        fragmentList.add(frag_b);
		        fragmentList.add(frag_c);
		        //設定介面卡  注意括號
		        pager.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
		            @Override
		            public Fragment getItem(int i) {
		                return fragmentList.get(i);
		            }
		
		            @Override
		            public int getCount() {
		                return titleList.size();
		            }
		
		            @Nullable
		            @Override
		            public CharSequence getPageTitle(int position) {
		                return titleList.get(position);
		            }
		        });
		        //設定模式
		        /**
		         * 注意 設定橫向模式
		         */
		        tabLayout.setTabMode(TabLayout.MODE_FIXED);
		        //將tablayout和viewpager結合
		        tabLayout.setupWithViewPager(pager);
		        return view;
		    }
		}