Android TabLayout實現頂部滑動效果(多個頁面)
阿新 • • 發佈:2019-03-04
hvie super title urn page nts bundle image 個數
1.design模式下,將TabLayout 拖入界面中
註意:TabLayout 在container中
2.design模式下,將ViewPager拖入界面中
<1>若出現錯誤(在xml文件中設置android:orientation="vertical")
<2>向viewpager中添加頁面組件
(1)創建多個頁面
app--->res--->layout ,選中layout,右擊new--->xml--->layout xml file
(2)將多個頁面布局添加到Viewpager中(采用Fragment的方式)
新建3個MyFragment(繼承Fragment)
public class MyFragment1 extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.layout_page1,container,false); return view; }
3.源碼
public class MainActivity extends AppCompatActivity { TabLayout tabLayout; ViewPager viewPager; List<Fragment> fragments; //定義一個列表集合(應用泛型) String[] table={"新聞","財經","娛樂"}; //定義一個數組存放標題內容 @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout=findViewById(R.id.tablayout); viewPager=findViewById(R.id.viewpager); fragments=new ArrayList<>(); //實例化集合 fragments.add(new MyFragment1()); fragments.add(new MyFragment2()); fragments.add(new MyFragment3()); Adapter adapter=new Adapter(getSupportFragmentManager(),fragments); //參數1為fragment管理器 viewPager.setAdapter(adapter); //給viewPager設置適配器 tabLayout.setupWithViewPager(viewPager); //將tabLayout與viewPager建立匹配 } //創建一個內部類作為適配器 public class Adapter extends FragmentPagerAdapter{ private List<Fragment> list; public Adapter(FragmentManager fm,List<Fragment> list) { super(fm); this.list=list; } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } //重寫getPageTitle()方法,獲取頁標題 @Nullable @Override public CharSequence getPageTitle(int position) { return table[position]; } } }
Android TabLayout實現頂部滑動效果(多個頁面)