011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

1.TabLayout介绍

  TabLayout提供了一个水平的布局用来展示Tabs,很多应用都有这样的设计,典型的有网易新闻,简书,知乎等。TabLayout就可以很好的完成这一职责,首先TabLayout一般都是配合Viewpager使用的,Viewpager里的Fragment随着顶部的Tab一起联动,这种场景再熟悉不过了。

注意:了解开源框架MagicIndicator,也能实现顶部菜单栏的功能。

参考文献:https://blog.csdn.net/qq_24956515/article/details/51871238

2.实现方法

(1)design模式下,将TabLayout 拖入界面中

注意:TabLayout 在container中

011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

(2)design模式下,将ViewPager拖入界面中

<1>若出现错误(在xml文件中设置android:orientation="vertical")

<2>向viewpager中添加页面组件

(1)创建多个页面

app--->res--->layout ,选中layout,右击new--->xml--->layout xml file

011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

(2)将多个页面布局添加到Viewpager中(采用Fragment的方式)

新建3个MyFragment(继承Fragment)

011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

注意:View类的介绍:在Activity显示的控件 都叫做View(View类 是所有的控件类的父类 比如 文本 按钮)

3.源码

<1>页面XML文件布局

(1)主页面

<?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=".MainActivity"> <android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

(2)fragment页面1布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"> <TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新闻页面"
android:textSize="30dp" />
</LinearLayout>

(3)fragment页面2布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"> <Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>

(4)fragment页面3布局

<?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"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"> <ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>

<2>后台代码

(1)MainActivity.java

package com.lucky.test11;

import android.support.annotation.Nullable;
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;
import java.util.List; 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];
}
}
}

(2)MyFragment1.java

package com.lucky.test11;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class MyFragment1 extends Fragment {
//将layout_pageq.xml文件与MyFragment1相关联
@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)MyFragment2.java

package com.lucky.test11;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class MyFragment2 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.layout_page2,container,false);
return view;
}
}

(4)MyFragment3.java

package com.lucky.test11;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; public class MyFragment3 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.layout_page3,container,false);
return view;
}
}

4.效果图

源码:test11

011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

5.使用案例二

本案例特点:根据网络请求返回的数据,自动生成tablayout中所要呈现的菜单项。

(1)NewsCenterFragment.java

package com.example.administrator.test66smartbeijing.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; import com.alibaba.fastjson.JSONObject;
import com.example.administrator.test66smartbeijing.R;
import com.example.administrator.test66smartbeijing.javabean.NewsMenu;
import com.example.administrator.test66smartbeijing.utils.CacheUtils;
import com.example.administrator.test66smartbeijing.utils.ConstantValue; import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x; /**
* 利用tabLayout+viewPager实现带顶部菜单栏的fragment
*/
public class NewsCenterFragment extends Fragment {
private TabLayout tabLayout = null;
private ViewPager viewPager;
private Fragment[] mFragmentArrays;
private String[] mTabTitles;
String queryResultStr="";
NewsMenu newsMenu; @Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.layout_fm_newscenter,container,false);
tabLayout = view.findViewById(R.id.tablayout);
viewPager = view.findViewById(R.id.tab_viewpager);
initView();
return view;
} private void initView() {
//判断有没有缓存,如果有的话,加载缓存,没有的话,请求网络数据
String cache=CacheUtils.getCache(ConstantValue.CATEGORY_URL,getActivity());
if(!TextUtils.isEmpty(cache)){
System.out.println("发现缓存");
newsMenu = processData(cache); }else {
getDataFromServer();
newsMenu =processData(queryResultStr);
}
System.out.println(newsMenu);
System.out.println(newsMenu.data.get(0).children.size());
mTabTitles = new String[newsMenu.data.get(0).children.size()]; //放置标题的数组 for (int i = 0; i <mTabTitles.length ; i++) {
mTabTitles[i]=newsMenu.data.get(0).children.get(i).title;
} //tabLayout.setTabMode(TabLayout.MODE_FIXED);
//设置tablayout距离上下左右的距离
//tab_title.setPadding(20,20,20,20);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); //设置tablayout为滚动模式
mFragmentArrays = new Fragment[mTabTitles.length]; for (int i = 0; i <mTabTitles.length ; i++) {
mFragmentArrays[i] = TabFragment.newInstance();
}
PagerAdapter pagerAdapter = new MyViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter); //给viewPager设置适配器
tabLayout.setupWithViewPager(viewPager);//将ViewPager和TabLayout绑定
} final class MyViewPagerAdapter extends FragmentPagerAdapter {
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
} //抽象方法必须重写(即子类必须实现父类的抽象方法)
@Override
public Fragment getItem(int position) {
return mFragmentArrays[position];
} @Override
public int getCount() {
return mFragmentArrays.length; } @Override
public CharSequence getPageTitle(int position) {
return mTabTitles[position]; //获取页标题
}
} /**
* 从服务器获取数据
*/
private void getDataFromServer() {
//请求地址
String url=ConstantValue.CATEGORY_URL;
RequestParams params = new RequestParams(url);
x.http().get(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {
//解析result
queryResultStr=result;
System.out.println(result); //写缓存
CacheUtils.setCache(ConstantValue.CATEGORY_URL,queryResultStr,getActivity());
}
//请求异常后的回调方法
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
//主动调用取消请求的回调方法
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
}); } private NewsMenu processData(String queryResultStr) {
// 复杂json格式字符串到JavaBean对象的转换
NewsMenu newsMenu = JSONObject.parseObject(queryResultStr,NewsMenu.class);
return newsMenu;
}
}

(2)TabFragment.java

package com.example.administrator.test66smartbeijing.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup; import com.example.administrator.test66smartbeijing.R;
import com.example.administrator.test66smartbeijing.utils.RecyclerAdapter; /**
* Created by zq on 2017/1/12.
*/
public class TabFragment extends Fragment { //新建一个Fragment实例
public static Fragment newInstance() {
TabFragment fragment = new TabFragment();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// LayoutInflater.inflate()的功能是将一段 XML 资源文件加载成为 View。所以通常用于将 XML 文件实例化为 View。然后获取 View 上的组件最后操作之。
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.recycler); //获取recyclerView这个组件
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager); //给recyclerView设置布局管理器
recyclerView.setAdapter(new RecyclerAdapter()); //给recyclerView设置适配器
return rootView;
}
}

(3)RecyclerAdapter.java

package com.example.administrator.test66smartbeijing.utils;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; import com.example.administrator.test66smartbeijing.R; /**
* Created by zq on 2017/1/12.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.AuthorViewHolder> { @Override
public AuthorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View childView = inflater.inflate(R.layout.item, parent, false);
AuthorViewHolder viewHolder = new AuthorViewHolder(childView);
return viewHolder;
} @Override
public void onBindViewHolder(AuthorViewHolder holder, int position) {
} @Override
public int getItemCount() {
return 15;
} class AuthorViewHolder extends RecyclerView.ViewHolder { TextView mNickNameView;
TextView mMottoView;
public AuthorViewHolder(View itemView) {
super(itemView);
mNickNameView = itemView.findViewById(R.id.tv_nickname);
mMottoView = itemView.findViewById(R.id.tv_motto);
}
}
}

(4)效果图

011 Android TabLayout+ViewPager实现顶部滑动效果(多个页面)

上一篇:使用FragmentTabHost+TabLayout+ViewPager实现双层嵌套Tab


下一篇:TabLayout + ViewPager