本文主要是介绍简单易懂,一步一步带你灵活运用ViewPager,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ViewPager概念
ViewPager是google SDK V4包中自带的一个视图类。主要作用:可以用来实现多个屏幕间的切换。
常用方法介绍
1.setAdapter(PagerAdapter adapter)
设置一个PagerAdapter,它将根据需要为这个页面提供视图
2.setCurrentItem(int item)
设置当前选定页面。如果viewPager已经通过它的当前设配器完成了它的第一个布局,那么当前item和指定item之间将会有一个平滑的动画过滤。
3.setOffscreenPageLimit(int limit)
在空闲状态下,在视图次结果中,设置应该保留到当前页面两侧的页面数量。超过这个限制的页面将要在需要时从适配器中重新创建。
4.addOnPageChangeListener(ViewPager.OnPageChangeListener listener)
增加一个监听器,每当页面发生变化或者不断的滑动时,都会被调用。
5.removeOnPageChangeListener(ViewPager.OnPageChangeListener listener)
删除之前通过addOnPageChangeListener(OnPageChangeListener)添加的监听器。
ViewPager入门实例讲解(每行代码都有注释,看着注释基本会懂意思。)
实现步骤:
1.在主布局文件里加入VierPager控件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent" ><android.support.v4.view.ViewPagerandroid:id="@+id/viewPager"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center" /></RelativeLayout>
2.新建三个布局文件,用来滑动切换视图
layout1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffffff"></LinearLayout>
layout2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffff00"></LinearLayout>
layout3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ff00ff"></LinearLayout>
3.Java代码实现
public class ViewPagerActivity extends AppCompatActivity {private ViewPager viewPager; //对应的ViewPager控件private View view1,view2,view3; //对应的三个Viewprivate List<View> viewList; //View数组@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_view_pager);initView();initData();}/*** 初始化控件*/private void initView() {viewPager = findViewById(R.id.viewPager);LayoutInflater inflater=getLayoutInflater();view1=inflater.inflate(R.layout.layout1,null);view2=inflater.inflate(R.layout.layout2,null);view3=inflater.inflate(R.layout.layout3,null);}/*** 设置数据*/private void initData() {//添加三个布局文件viewList=new ArrayList<>();viewList.add(view1);viewList.add(view2);viewList.add(view3);//设置适配器viewPager.setAdapter(pagerAdapter);}//初始化PagerAdapter设配器PagerAdapter pagerAdapter=new PagerAdapter(){//返回要滑动的View的个数@Overridepublic int getCount() {return viewList.size();}//判断当前的View是否是instantiateItem添加的View@Overridepublic boolean isViewFromObject(@NonNull View view, @NonNull Object object) {return view==object;}//从当前container中删除指定位置(position)的View;@Overridepublic void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {container.removeView(viewList.get(position));}//第一:将当前视图添加到container中,第二:返回当前View@NonNull@Overridepublic Object instantiateItem(@NonNull ViewGroup container, int position) {container.addView(viewList.get(position));return viewList.get(position);}};
}
ViewPager进阶实例讲解
注:这是在入门实例基础上进阶的实例(使用Fragment实现ViewPager滑动页面)。
实现步骤:
- 实现设配器(FragmentPagerAdapter 或者 FragmentStatePagerAdapter)
注:FragmentPagerAdapter 和 FragmentStatePagerAdapter都是PagerAdapter的子类。主要的区别:FragmentStatePagerAdapter处理大量的页面切换,而FragmentPagerAdapter处理有限个静态Fragment页面。我们这里就使用FragmentStatePagerAdapter做讲解。
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.List;public class FragAdapter extends FragmentStatePagerAdapter {private List<Fragment> mFragments;//Fragment数组,用于保存用于滑动的Fragment对象public FragAdapter(FragmentManager fm,List<Fragment> fragments) {super(fm);mFragments=fragments;}//返回指定位置关联的Fragment@Overridepublic Fragment getItem(int position) {return mFragments.get(position);}//返回用于滑动的Fragment总数@Overridepublic int getCount() {return mFragments.size();}
}
- 新建三个fragment类
2.1第一个Fragment
XML(layout1.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffffff"></LinearLayout>
JAVA代码
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;
import com.example.lenovo.androidtest.R;public class Fragment1 extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {return inflater.inflate(R.layout.layout1, container, false);}
}
2.2第二个Fragment
XML(layout2.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffff00"></LinearLayout>
JAVA代码
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;import com.example.lenovo.androidtest.R;public class Fragment2 extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {return inflater.inflate(R.layout.layout2, container, false);}
}
2.3第三个Fragment
XML(layout3.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ff00ff"></LinearLayout>
JAVA代码
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;import com.example.lenovo.androidtest.R;public class Fragment3 extends Fragment {@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {return inflater.inflate(R.layout.layout3, container, false);}
}
注:其实大家发现没有,相对于入门级的布局文件,只是多了三个Fragment类来加载三个页面。
- Activity代码实现
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;import com.example.lenovo.androidtest.R;
import com.example.lenovo.androidtest.adapter.FragAdapter;
import com.example.lenovo.androidtest.fragment.Fragment1;
import com.example.lenovo.androidtest.fragment.Fragment2;
import com.example.lenovo.androidtest.fragment.Fragment3;import java.util.ArrayList;
import java.util.List;public class ViewPagerFragmentActivity extends AppCompatActivity {ViewPager vp;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_view_pager_fragment);initView();initData();}private void initView() {vp = findViewById(R.id.all_viewPage); //获取viewpage控件}private void initData() {List<Fragment> fragments=new ArrayList<>(); //构建一个Fragment列表//将三个Fragment实例添加到List中fragments.add(new Fragment1()); fragments.add(new Fragment2());fragments.add(new Fragment3());//生成一个FragAdapter实例FragAdapter adapter = new FragAdapter(getSupportFragmentManager(), fragments);//设定适配器vp.setAdapter(adapter);}
}
总结:其实进阶的实例只是在入门实例上用Fragment实现了同样的效果。上面的实例注意了,一定要导入V4包里面的Fragment。不然的话,List添加实例的时候会提示“无法将Fragment()转换为fragment”。
ViewPager应用(ViewPager+Fragment+TabLayout+RecyclerView)
注:现在就是带你实现平时我们开发中用得最多的黄金搭配了。ViewPager+Fragment+TabLayout+RecyclerView最强组合。
实现步骤:
1.1.新建Fragment布局文件(fragment_item_list)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView 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:id="@+id/list"android:name="com.example.lenovo.androidtest.fragment.ItemFragment"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginLeft="16dp"android:layout_marginRight="16dp"app:layoutManager="LinearLayoutManager"tools:context=".fragment.ItemFragment"tools:listitem="@layout/fragment_item" />
1.2新建Fragment类(ItemFragment)
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
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.lenovo.androidtest.R;
import com.example.lenovo.androidtest.fragment.dummy.DummyContent;public class ItemFragment extends Fragment {// 对应页面标识名称private static final String ARG_COLUMN_COUNT = "column-count";// 对应页面标识private int mColumnCount = 1;public ItemFragment() {}//实例化ItemFragment,并且传入标识参数@SuppressWarnings("unused")public static ItemFragment newInstance(int columnCount) {ItemFragment fragment = new ItemFragment();Bundle args = new Bundle();args.putInt(ARG_COLUMN_COUNT, columnCount);fragment.setArguments(args);return fragment;}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);if (getArguments() != null) {mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);//获取标识参数}}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_item_list, container, false);if (view instanceof RecyclerView) { //判断是否是RecyclerView控件Context context = view.getContext();RecyclerView recyclerView = (RecyclerView) view;//如果参数值小于等于1,就设置为线型列表,否则就是设置表格列表if (mColumnCount <= 1) {recyclerView.setLayoutManager(new LinearLayoutManager(context));} else {recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));}//设置列表设配器recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS));}return view;}
}
2.1添加RecyclerView适配器(布局文件我就不写了)
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.lenovo.androidtest.R;
import com.example.lenovo.androidtest.fragment.dummy.DummyContent.DummyItem;
import java.util.List;public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {private final List<DummyItem> mValues;public MyItemRecyclerViewAdapter(List<DummyItem> items) {mValues = items;}@Overridepublic ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_item, parent, false);return new ViewHolder(view);}@Overridepublic void onBindViewHolder(final ViewHolder holder, int position) {holder.mItem = mValues.get(position);holder.mIdView.setText(mValues.get(position).id);holder.mContentView.setText(mValues.get(position).content);}@Overridepublic int getItemCount() {return mValues.size();}public class ViewHolder extends RecyclerView.ViewHolder {public final View mView;public final TextView mIdView;public final TextView mContentView;public DummyItem mItem;public ViewHolder(View view) {super(view);mView = view;mIdView = (TextView) view.findViewById(R.id.item_number);mContentView = (TextView) view.findViewById(R.id.content);}@Overridepublic String toString() {return super.toString() + " '" + mContentView.getText() + "'";}}
}
3.1Activity核心代码
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.lenovo.androidtest.R;
import com.example.lenovo.androidtest.common.TabFragmentIndex;
import com.example.lenovo.androidtest.fragment.FragmentAdapter;
import com.example.lenovo.androidtest.fragment.ItemFragment;
import java.util.ArrayList;
import java.util.List;public class NewParentActivity extends AppCompatActivity{private ViewPager mViewpager; //ViewPager控件private TabLayout mTabLayout; //TabLayout控件private String[] tabs = new String[]{"首页","推荐","热点"}; //标题要显示的文字protected List<Fragment> fragments; //Fragment的List集合@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.test);initView();initData();}/*** 初始化控件*/private void initView() {mTabLayout = findViewById(R.id.tabs);mViewpager = findViewById(R.id.viewpager);}/*** 初始化数据*/private void initData() {fragments = new ArrayList<>(); //实例化fragment集合for (int i = 0; i < tabs.length; i++) {mTabLayout.addTab(mTabLayout.newTab().setText(tabs[i])); //添加Tab,并且设置标题文字//添加三个Fragment实例switch (i) {case 0:fragments.add(ItemFragment.newInstance(0));break;case 1:fragments.add(ItemFragment.newInstance(1));break;case 2:fragments.add(ItemFragment.newInstance(2));break;}}mViewpager.setAdapter(new FragmentAdapter(getSupportFragmentManager(), fragments)); //设置ViewPager设配器mViewpager.setCurrentItem(1); //设置当前选定页面(这里的值是1,代表初始化是第二个页面)mViewpager.setOffscreenPageLimit(2); //缓存页面个数(这里是缓存了两个页面,)mTabLayout.setupWithViewPager(mViewpager); //建立TabLayout与ViewPager关联,(就是这么牛,一句代码解决关联代码)for (int i = 0; i < tabs.length; i++)mTabLayout.getTabAt(i).setText(tabs[i]);//这个地方主要是解决ViewPager设置设配器的时候,把TabLayout的标题文字给置空问题。}
}
好了,关于ViewPager的入门到应用的实例就到此结束了。有关TabLayout和RecyclerView的介绍,大家可以到网上搜索具体的用法。关于上面的几个实例有什么疑问或者错误,欢迎在评论区留言。
这篇关于简单易懂,一步一步带你灵活运用ViewPager的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!