<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.a85469.myapplication.MainActivity">
<!--填充整个页面的ViewPager-->
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"//划重点
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="200dp">
</android.support.design.widget.TabLayout>
</android.support.constraint.ConstraintLayout>
import android.content.Context;
import android.os.Bundle;
import android.provider.SyncStateContract;
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.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
MyAdapter myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
//tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_bianji));
//tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_xuanze));
tabLayout.getTabAt(0).setIcon(R.drawable.ic_bianji);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_xuanze);
}
/**
* 自定义类实现PagerAdapter,填充显示数据
*/
class MyAdapter extends PagerAdapter {
// 显示多少个页面
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
// 初始化显示的条目对象
@Override
public Object instantiateItem(ViewGroup container, int position) {
// return super.instantiateItem(container, position);
// 准备显示的数据,一个简单的TextView
TextView tv = new TextView(MainActivity.this);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(20);
int positions = position+1;
tv.setText("这是第" + positions + "页");
// 添加到ViewPager容器
container.addView(tv);
// 返回填充的View对象
return tv;
}
// 销毁条目对象
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
}
}