第一步布局:
<android.support.v4.view.ViewPager
android:id="@+id/home_vp"
android:layout_width=“match_parent”
android:layout_above="@id/home_tab"
android:layout_height=“wrap_content”></android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:id="@+id/home_tab"
android:layout_width=“match_parent”
android:layout_alignParentBottom=“true”
app:tabIndicatorHeight="@dimen/dp_0"
android:layout_height="@dimen/dp_49"></android.support.design.widget.TabLayout>
第二布创建对应的fragment和在Activity中findViewById:
public class HomePageActivity extends AppCompatActivity {
private ViewPager home_vp;
private TabLayout home_tab;
private ArrayList<Fragment> fragments=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
initView();
initData();
}
public void initData() {
HomePageFragment homePageFragment = new HomePageFragment();
MessageFragment messageFragment = new MessageFragment();
AddressBookFragment addressBookFragment = new AddressBookFragment();
MyFragment myFragment = new MyFragment();
fragments.add(homePageFragment);
fragments.add(messageFragment);
fragments.add(addressBookFragment);
fragments.add(myFragment);
home_vp.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int i) {
return fragments.get(i);
}
@Override
public int getCount() {
return fragments.size();
}
});
home_tab.setupWithViewPager(home_vp);
home_tab.getTabAt(0).setIcon(getResources().getDrawable(R.mipmap.home)).setText("首页");
home_tab.getTabAt(1).setIcon(getResources().getDrawable(R.mipmap.tongzhi_none)).setText("通知公告");
home_tab.getTabAt(2).setIcon(getResources().getDrawable(R.mipmap.tongxunlu_none)).setText("通讯录");
home_tab.getTabAt(3).setIcon(getResources().getDrawable(R.mipmap.tongxunlu_none_copy)).setText("我的");
}
public void initView() {
home_vp=findViewById(R.id.home_vp);
home_tab=findViewById(R.id.home_tab);
}
}
方便自己记忆 长时间不看 什么都会忘记的