先看一下效果
tablayout+viewpager+fragment 这种界面搭建 也算是目前界面中的一个主流 市场上可以说是占据了
半壁江山 设计简洁明了 功能显著 开发者搭建起来也很简单 下面直接上代码 首先要先添加两个依赖
首先要先添加两个依赖
compile ‘com.android.support:support-v4:25.3.0’ // v4包
compile ‘com.android.support:design:25.3.1’ // design包
activity 的 xml 文件
LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical”>
android.support.design.widget.TabLayout
android:layout_width=”match_parent”
android:layout_height=”50dp”
android:background=”#d5f9f3”
app:tabIndicatorColor=”#ff6c2a”
app:tabMode=”fixed”
app:tabSelectedTextColor=”#ff6c2a”
app:tabTextColor=”#999999”
android:id=”@+id/tab_layout”>
android.support.v4.view.ViewPager
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/view_pager”>
/LinearLayout>
activity 代码片
初始化view 然后绑定数据
private TabLayout tab_layout;
private ViewPager view_pager;
private String[]tabs = new String[]{“首页”,”消息”,”我的”};// title数组
private List fragList = new ArrayList<>(); // fragment 集合
private HomeFragment homeFragment;
private MineFragment mineFragment;
private MessageFragment messageFragment;
public class PagerAndFragmentActivity extends FragmentActivity {
private TabLayout tab_layout;
private ViewPager view_pager;
private String[]tabs = new String[]{"首页","消息","我的"};// title数组
private List fragList = new ArrayList<>(); // fragment 集合
private HomeFragment homeFragment;
private MineFragment mineFragment;
private MessageFragment messageFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_and_fragment);
tab_layout = (TabLayout) findViewById(R.id.tab_layout);
view_pager = (ViewPager) findViewById(R.id.view_pager);
// 创建fragment对象
homeFragment = new HomeFragment();
mineFragment = new MineFragment();
messageFragment = new MessageFragment();
fragList.add(homeFragment);
fragList.add(mineFragment);
fragList.add(messageFragment);
view_pager.setCurrentItem(0);
view_pager.setAdapter(new MyFrageStatePagerAdapter(getSupportFragmentManager()));
// 将viewpager 设置给tablayout
tab_layout.setupWithViewPager(view_pager);
}
// viewpager 的 adapter
private class MyFrageStatePagerAdapter extends FragmentStatePagerAdapter {
public MyFrageStatePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragList.get(position);
}
@Override
public int getCount() {
return fragList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
代码部分很简单 fragment 就是你的app 数据内容 本文使用的是show 和 hint 的方式控制fragment 防止 fragment 重叠和 数据切换刷新问题
重写 防止重影
@Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}
重写 fragment 切换刷新
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
好了 本文完结 如有疑问 欢迎评论或私信