TabLayout的基本使用结合Viewpager(Android开发)

xml文件:


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"
    tools:context="com.example.day014_tablayout.MainActivity">


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

    <android.support.v4.view.ViewPager
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/vp">android.support.v4.view.ViewPager>

LinearLayout>
 
  
 
  
主代码:
 
  
 
  
 
  
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private TabLayout tl;
    private ViewPager vp;
    ArrayList list = new ArrayList<>();
    ArrayList titlelist  = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取控件
        tl = (TabLayout) findViewById(R.id.tl);
        vp = (ViewPager) findViewById(R.id.vp);
        //数据
        initData();
        //适配器
        Myadpater md = new Myadpater(getSupportFragmentManager());
        vp.setAdapter(md);

        //标签居中显示
        tl.setTabMode(TabLayout.MODE_FIXED);
        //viewpeger与TabLayout关联
        tl.setupWithViewPager(vp);
    }

    //获取数据
    private void initData() {
        for (int i = 0; i < 5; i++) {
            list.add(new Frag1());
            titlelist.add("标题"+i);
        }
    }

    private class Myadpater extends FragmentPagerAdapter {
        public Myadpater(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
        //返回标题 ,CharSequence:是个接口, String是它的实现了;

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

 
  
 
  

你可能感兴趣的:(android)