必威体育Betway必威体育官网
当前位置:首页 > IT技术

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

时间:2019-10-10 01:12:19来源:IT技术作者:seo实验室小编阅读:68次「手机版」
 

viewpager

最近在找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>

相关阅读

DX11 游戏开发笔记 (二) DX11 基础框架 上

必须吐槽csdn的排版,真的是对不起它的名字! 抱了很大的决心,才决定写下这篇博文,笔者大三从其它专业转行,学习c c++也就一年多,因为入了

Java - 持久层设计要考虑的问题有哪些?你用过的持久层

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net  所谓

Prism for WPF 搭建一个简单的模块化开发框架(一)

最近闲来无事又想搞搞WPF。。。。。做个框架吧,可能又是半途而废。。。。总是坚持不下来 不废话了, 先看一下工程结构 布局大概是

JAVA学习必须掌握的框架和技术,不看后悔

转载自:https://blog.csdn.net/jackyrongvip/article/details/82148922 Web应用,最常见的研发语言是Java和PHP。 后端服务,最常见的

基础的unity局域网游戏框架(一)

最近看了下关于unity的网络模块netwrok即将淘汰,思索了下准备自己用socket去封装个局域网的通讯插件 看了一下关于同步问题 https:

分享到:

栏目导航

推荐阅读

热门阅读