Bootstrap

(超详细)超炫酷的ViewPager框架——MaterialViewPager使用方法详解

最近在找viewpager开源框架的时候,发现了一款十分炫酷的框架——MaterialViewPager

少说废话,先贴实际效果图:

         

原项目地址(含Demo)https://github.com/florent37/MaterialViewPager

我在这里只是介绍它的基本使用,更多关于它的自定义效果还请阅读原项目。

使用方法:

1、导包

向你的build.gradle(Module:app)中的dependencies闭包下添加以下代码

compile 'com.github.florent37:materialviewpager:1.2.3'

//dependencies
compile 'com.flaviofaria:kenburnsview:1.0.7'
compile 'com.jpardogo.materialtabstrip:library:1.1.0'
compile 'com.github.bumptech.glide:glide:4.0.0'

2、在你的layout中加入MaterialViewPager控件

<com.github.florent37.materialviewpager.MaterialViewPager
    android:id="@+id/materialViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:viewpager_logo="@layout/header_logo"
    app:viewpager_logoMarginTop="100dp"
    app:viewpager_color="@color/colorPrimary"
    app:viewpager_headerHeight="200dp"
    app:viewpager_headerAlpha="1.0"
    app:viewpager_hideLogoWithFade="false"
    app:viewpager_hideToolbarAndTitle="true"
    app:viewpager_enableToolbarElevation="true"
    app:viewpager_parallaxHeaderFactor="1.5"
    app:viewpager_headerAdditionalHeight="20dp"
    app:viewpager_displayToolbarWhenSwipe="true"
    app:viewpager_transparentToolbar="true"
    app:viewpager_animatedHeaderImage="true"
    app:viewpager_disableToolbar="false"

    />
  • MaterialViewPager继承自FrameLayout,所以继承了FrameLayout的某些特性。
  • 通过调整以上代码中false/true可以实现一些自定义的效果,具体哪一句话有什么用,还请大家亲自去尝试,此文章不详细介绍。

3、在layout中建立header_logo.xml文件

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/logo_white"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/materialviewpager_logoHeight"
    android:text="Material is Good"
    android:textSize="30sp"
    android:textColor="@android:color/white"/>

4、修改你的AppTheme主题

具体方法:

  • 将你的AndroidManifest.xml设置android:theme="@style/AppTheme"
  • 将你的values文件夹下的styles.xml替换成以下代码
<resources xmlns:tools="http://schemas.android.com/tools">

    <!-- Base application theme. -->
    <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light">
    </style>

    <style name="AppTheme" parent="AppBaseTheme">

        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
        <item name="android:windowTranslucentStatus" tools:targetApi="21">true</item>

        <item name="android:windowContentOverlay">@null</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>

        <!-- Toolbar Theme / Apply white arrow -->
        <item name="colorControlNormal">@android:color/white</item>
        <item name="actionBarTheme">@style/AppTheme.ActionBarTheme</item>

        <!-- Material Theme -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/accent_color</item>

        <item name="android:navigationBarColor" tools:targetApi="21">@color/navigationBarColor</item>
        <item name="android:windowDrawsSystemBarBackgrounds" tools:targetApi="21">true</item>

    </style>

    <style name="AppTheme.ActionBarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">
        <!-- White arrow -->
        <item name="colorControlNormal">@android:color/white</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@color/drawerArrowColor</item>
    </style>

</resources>

5、找到你的MaterialViewPager

像一个普通的view一样,可以通过findviewById得到实例

public class MainActivity extends ActionBarActivity {

    private MaterialViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = (MaterialViewPager) findViewById(R.id.materialViewPager);
    }
}
  • 此时在Preview中你会看到以下的预览图

 

好了,到这里我们的前期准备工作就已经结束了,下面便是让你的项目靓起来的重头戏。在这之前我们首先回顾一下,看你是否有所遗漏。

  1. 导包,这个肯定忘不了,因为如果没有这个,项目都是红线,看着心里就发毛,程序员的职业病
  2. 将控件MaterialViewPager导入你的layout
  3. 建立header_logo.xml
  4. 修改AndroidManifest.xml与styles.xml
  5. 通过findviewById获取实例

1、为你的MaterialViewPager添加监听

mViewPager.setMaterialViewPagerListener(new MaterialViewPager.Listener() {
            @Override
            public HeaderDesign getHeaderDesign(int page) {
                switch (page) {
                    case 0:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.blue,
                                "http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2014/06/wallpaper_51.jpg");
                    case 1:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.green,
                                "https://fs01.androidpit.info/a/63/0e/android-l-wallpapers-630ea6-h900.jpg");
                    case 2:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.cyan,
                                "http://www.droid-life.com/wp-content/uploads/2014/10/lollipop-wallpapers10.jpg");
                    case 3:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.red,
                                "http://www.tothemobile.com/wp-content/uploads/2014/07/original.jpg");
                }

                //execute others actions if needed (ex : modify your header logo)

                return null;
            }
        });

HeaderDesign有四个设置背景的方法,可以按自己的需求选择合适的方法(用上边的方法不联网是看不到图片的哦)

HeaderDesign.fromColorAndUrl(Color.BLUE,"http:...);
HeaderDesign.fromColorResAndUrl(R.color.blue,"http:...);
HeaderDesign.fromColorAndDrawable(Color.BLUE,myDrawable);
HeaderDesign.fromColorResAndDrawable(R.color.blue,myDrawable);

 

 

 

2、设置Toolbar

Toolbar toolbar = mViewPager.getToolbar();

if (toolbar != null) {
     setSupportActionBar(toolbar);

     ActionBar actionBar = getSupportActionBar();
     actionBar.setDisplayHomeAsUpEnabled(true);
     actionBar.setDisplayShowHomeEnabled(true);
     actionBar.setDisplayShowTitleEnabled(true);
     actionBar.setDisplayUseLogoEnabled(false);
     actionBar.setHomeButtonEnabled(true);
}

 

3、为你的viewpager设置适配器

ViewPager viewPager = mViewPager.getViewPager();
viewPage.setAdapter(...);

//在设置adapter之后设置
mViewPager.getPagerTitleStrip().setViewPager(mViewPager.getViewPager());

 

4、在你的RecycleViewFragment类中添加

mRecyclerView.addItemDecoration(new MaterialViewPagerHeaderDecorator());
mRecyclerView.setAdapter(yourAdapter);

至此便完成了。

什么?你还没有看懂?我写了一个Demo供大家参考,项目地址https://github.com/theazet/MaterialViewPagerDemo

我也把项目代码贴在了这里

 

首先放上项目各文件结构

文件内具体代码

  • MainActivity

 

package com.example.materialviewpagerdemo;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.github.florent37.materialviewpager.MaterialViewPager;
import com.github.florent37.materialviewpager.header.HeaderDesign;

public class MainActivity extends AppCompatActivity {
    private MaterialViewPager mViewPager;
    static final int TAPS = 3;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = findViewById(R.id.materialViewPager);
        //添加监听
        mViewPager.setMaterialViewPagerListener(new MaterialViewPager.Listener() {
            @Override
            public HeaderDesign getHeaderDesign(int page) {
                switch (page) {
                    case 0:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.blue,
                                "http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2014/06/wallpaper_51.jpg");
                    case 1:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.green,
                                "https://fs01.androidpit.info/a/63/0e/android-l-wallpapers-630ea6-h900.jpg");
                    case 2:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.cyan,
                                "http://www.droid-life.com/wp-content/uploads/2014/10/lollipop-wallpapers10.jpg");
                    case 3:
                        return HeaderDesign.fromColorResAndUrl(
                                R.color.red,
                                "http://www.tothemobile.com/wp-content/uploads/2014/07/original.jpg");
                }

                //execute others actions if needed (ex : modify your header logo)

                return null;
            }
        });
        //设置Toolbar
        Toolbar toolbar = mViewPager.getToolbar();

        if (toolbar != null) {
            setSupportActionBar(toolbar);

            ActionBar actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setDisplayUseLogoEnabled(false);
            actionBar.setHomeButtonEnabled(true);
        }

        //设置Adapter
        mViewPager.getViewPager().setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                switch (position % TAPS) {
                    case 0:
                        return RecyclerViewFragment.newInstance();

                    default:
                        return RecyclerViewFragment.newInstance();
                }
            }

            @Override
            public int getCount() {
                return TAPS;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position % TAPS) {
                    case 0:
                        return "TAP1";


                    default:
                        return "TAPN";
                }
            }
        });
        //设置setViewPager
        mViewPager.getViewPager().setOffscreenPageLimit(mViewPager.getViewPager().getAdapter().getCount());
        mViewPager.getPagerTitleStrip().setViewPager(mViewPager.getViewPager());
    }
}
  • RecyclerViewFragment
package com.example.materialviewpagerdemo;

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.github.florent37.materialviewpager.header.MaterialViewPagerHeaderDecorator;

import java.util.ArrayList;
import java.util.List;

public class RecyclerViewFragment extends Fragment {
    public static Fragment newInstance(){return  new RecyclerViewFragment();}
    final List<Object> items = new ArrayList<>();
    static final int ITEMS = 3;

    RecyclerView mRecyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recyclerview, container, false);
    }
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView=view.findViewById(R.id.recyclerView);
        for (int i=0;i<ITEMS;i++){
            items.add(new Object());

        }


        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new MaterialViewPagerHeaderDecorator());
        mRecyclerView.setAdapter(new RecyclerViewPagerAdapter(items));
    }
}
  • RecyclerViewPagerAdapter
package com.example.materialviewpagerdemo;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

public class RecyclerViewPagerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    List<Object> contents;
    public RecyclerViewPagerAdapter(List<Object> contents) {
        this.contents = contents;
    }
    public int getItemCount() {
        return contents.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.content_cardview, parent, false);

        return new RecyclerView.ViewHolder(view) {
        };

    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

}
  • activity_main
<?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=".MainActivity">

    <com.github.florent37.materialviewpager.MaterialViewPager
        android:id="@+id/materialViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:viewpager_logo="@layout/header_logo"
        app:viewpager_logoMarginTop="100dp"
        app:viewpager_color="@color/colorPrimary"
        app:viewpager_headerHeight="200dp"
        app:viewpager_headerAlpha="1.0"
        app:viewpager_hideLogoWithFade="false"
        app:viewpager_hideToolbarAndTitle="true"
        app:viewpager_enableToolbarElevation="true"
        app:viewpager_parallaxHeaderFactor="1.5"
        app:viewpager_headerAdditionalHeight="20dp"
        app:viewpager_displayToolbarWhenSwipe="true"
        app:viewpager_transparentToolbar="true"
        app:viewpager_animatedHeaderImage="true"
        app:viewpager_disableToolbar="false"

        />

</android.support.constraint.ConstraintLayout>

 

content_cardview(别忘了导入cardview的依赖)

 

compile group: 'com.android.support', name: 'cardview-v7', version: '28.0.0-alpha3'
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginBottom="@dimen/cardMarginVertical"
        android:layout_marginLeft="@dimen/cardMarginHorizontal"
        android:layout_marginRight="@dimen/cardMarginHorizontal"
        android:layout_marginTop="@dimen/cardMarginVertical"
        app:cardCornerRadius="2dp"
        app:cardElevation="2dp"
        app:cardPreventCornerOverlap="false"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackgroundBorderless"
        app:contentPadding="0dp">
    </android.support.v7.widget.CardView>

</FrameLayout>
  • fragment_recyclerview
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
  • header_logo
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/logo_white"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/materialviewpager_logoHeight"
    android:text="Material is Good"
    android:textSize="30sp"
    android:textColor="@android:color/white"/>
  • style.xml
<resources xmlns:tools="http://schemas.android.com/tools">

    <!-- Base application theme. -->
    <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light">
    </style>

    <style name="AppTheme" parent="AppBaseTheme">

        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
        <item name="android:windowTranslucentStatus" tools:targetApi="21">true</item>

        <item name="android:windowContentOverlay">@null</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>

        <!-- Toolbar Theme / Apply white arrow -->
        <item name="colorControlNormal">@android:color/white</item>
        <item name="actionBarTheme">@style/AppTheme.ActionBarTheme</item>

        <!-- Material Theme -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/accent_color</item>

        <item name="android:navigationBarColor" tools:targetApi="21">@color/navigationBarColor</item>
        <item name="android:windowDrawsSystemBarBackgrounds" tools:targetApi="21">true</item>

    </style>

    <style name="AppTheme.ActionBarTheme" parent="@style/ThemeOverlay.AppCompat.ActionBar">
        <!-- White arrow -->
        <item name="colorControlNormal">@android:color/white</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@color/drawerArrowColor</item>
    </style>

</resources>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

;