Android AppBarLayout+TabLayout+RecyclerView+ViewPager+Fragment

最近有人让我帮忙实现一个如下图所示的效果

需求:标题栏本来是在banner的下方,当滑动下面的RecyclerView的时候标题栏会随着向上移动,但是当标题栏移动到顶部时是要悬浮在顶部,下面无论如何上滑标题拦都不再移动,当向下滑动时知直到出现RecyclerView的第一条时标题栏才会随着向下移动。
AppBarLayout 是继承LinerLayout实现的一个ViewGroup容器组件,它是为了Material Design设计的App Bar,支持手势滑动操作。CoordinatorLayout是一个增强型的FrameLayout。它的作用有两个作为一个布局的根布局 最后一个为子视图之间相互协调手势效果的一个协调布局
为了达到上面效果图的手势动画效果,我们必须做如下设置,通过app:layout_scrollFlags=”scroll” 属性来确定哪个组件是可滑动的
设置的layout_scrollFlags有如下几种选项:
scroll: 所有想滚动出屏幕的view都需要设置这个flag- 没有设置这个flag的view将被固定在屏幕顶部。 enterAlways: 这个flag让任意向下的滚动都会导致该view变为可见,启用快速“返回模式”。 enterAlwaysCollapsed: 当你的视图已经设置minHeight属性又使用此标志时,你的视图只能已最小高度进入,只有当滚动视图到达顶部时才扩大到完整高度。 exitUntilCollapsed: 滚动退出屏幕,最后折叠在顶端。
我们上面的布局中 给Toolbar设置了app:layout_scrollFlags属性,因此,Toolbar是可以滚动出屏幕,且向下滚动有可以出现。
具体实现的代码如下

package com.lyx.demo.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;


import com.lyx.demo.adapter.MyRecyclerViewAdapter;
import com.lyx.demo.R;
import com.lyx.demo.listener.MyItemClickListener;
import com.lyx.demo.view.LoadMoreRecyclerView;

public class FragmentPopularity extends Fragment {
    private View view;
    private SwipeRefreshLayout swipeRefreshLayout;
    private static FragmentPopularity instance=null;
    public static FragmentPopularity newInstance() {
        if(instance==null){
            instance= new FragmentPopularity();
        }
        return instance;
    }
    public FragmentPopularity(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_layout, container, false);
        final LoadMoreRecyclerView mRecyclerView = (LoadMoreRecyclerView) view.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        int[]mImgList = new int[]{R.drawable.g1,R.drawable.g2,R.drawable.g3,R.drawable.g4,R.drawable.g5,R.drawable.g6,R.drawable.g7,R.drawable.g8,R.drawable.g9,R.drawable.g10};
        String [] mTag = getActivity().getResources().getStringArray(R.array.test);
        MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(getActivity(),mImgList,mTag);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                Toast.makeText(getActivity(),"test"+postion,Toast.LENGTH_SHORT).show();
            }
        });
        mRecyclerView.setAutoLoadMoreEnable(true);
        mRecyclerView.setLoadMoreListener(new LoadMoreRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                mRecyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                        Toast.makeText(getActivity(),"加载更多",Toast.LENGTH_SHORT).show();
                        //TODO 下面注释掉的代码中的false是当数据加载完成以后为false的,然后加载更多的条目就会隐藏。
//                        mRecyclerView.notifyMoreFinish(false);
                    }
                }, 1000);
            }
        });
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getActivity(),"刷新",Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}

其他的fragment内容都是复制的这个fragment的
下面的是主activity的

package com.lyx.demo.activities;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lyx.demo.R;
import com.lyx.demo.adapter.BannerAdapter;
import com.lyx.demo.adapter.MyViewPagerAdapter;
import com.lyx.demo.fragment.FragmentLowPrice;
import com.lyx.demo.fragment.FragmentHighPrice;
import com.lyx.demo.fragment.FragmentPopularity;
import com.lyx.demo.fragment.FragmentSecondsOpen;
import com.lyx.demo.fragment.FragmentNewProduct;
import com.lyx.demo.utils.DensityUtil;

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


public class MainActivity extends AppCompatActivity {
    LinearLayout llIndexContainer;
    private List mADParseArray;
    private final int HOME_AD_RESULT = 1;
    private ViewPager vp_shuffling;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 广告
                case HOME_AD_RESULT:
                    vp_shuffling.setCurrentItem(vp_shuffling.getCurrentItem() + 1,
                            true);
                    break;
            }
        };
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
        MyViewPagerAdapter viewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragment(FragmentPopularity.newInstance(), "人气");//添加Fragment
        viewPagerAdapter.addFragment(FragmentNewProduct.newInstance(), "新品");
        viewPagerAdapter.addFragment(FragmentSecondsOpen.newInstance(), "秒开");
        viewPagerAdapter.addFragment(FragmentHighPrice.newInstance(), "高价");
        viewPagerAdapter.addFragment(FragmentLowPrice.newInstance(), "低价");
        mViewPager.setAdapter(viewPagerAdapter);//设置适配器

        TabLayout mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        mTabLayout.addTab(mTabLayout.newTab().setText("人气"));//给TabLayout添加Tab
        mTabLayout.addTab(mTabLayout.newTab().setText("新品"));
        mTabLayout.addTab(mTabLayout.newTab().setText("秒开"));
        mTabLayout.addTab(mTabLayout.newTab().setText("高价"));
        mTabLayout.addTab(mTabLayout.newTab().setText("低价"));
        mTabLayout.setupWithViewPager(mViewPager);//给TabLayout设置关联ViewPager,如果设置了ViewPager,那么ViewPagerAdapter中的getPageTitle()方法返回的就是Tab上的标题
    }

    private void initView() {
        vp_shuffling = (ViewPager) findViewById(R.id.vp_shuffling);
        // 广告数据
        llIndexContainer = (LinearLayout)findViewById(R.id.ll_index_container);
        mADParseArray = new ArrayList();
        mADParseArray
                .add("http://m.easyto.com/m/zhulifuwu_banner.jpg");
        mADParseArray
                .add("http://m.easyto.com/m/japan/images/banner_3y_new.jpg");
        mADParseArray
                .add("http://m.easyto.com/m/japan/images/banner_5y_new.jpg");
        vp_shuffling.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                refreshPoint(position % mADParseArray.size());
                if (mHandler.hasMessages(HOME_AD_RESULT)) {
                    mHandler.removeMessages(HOME_AD_RESULT);
                }
                mHandler.sendEmptyMessageDelayed(HOME_AD_RESULT, 3000);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (ViewPager.SCROLL_STATE_DRAGGING == arg0
                        && mHandler.hasMessages(HOME_AD_RESULT)) {
                    mHandler.removeMessages(HOME_AD_RESULT);
                }
            }
        });
        BannerAdapter adapter = new BannerAdapter(MainActivity.this, mADParseArray);
        vp_shuffling.setAdapter(adapter);
        addIndicatorImageViews(mADParseArray.size());
        vp_shuffling.setCurrentItem(mADParseArray.size() * 1000, false);
        // 自动轮播线程
        mHandler.sendEmptyMessageDelayed(HOME_AD_RESULT, 3000);
    }
    // 添加指示图标
    private void addIndicatorImageViews(int size) {
        llIndexContainer.removeAllViews();
        for (int i = 0; i < size; i++) {
            ImageView iv = new ImageView(MainActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(MainActivity.this, 5), DensityUtil.dip2px(MainActivity.this, 5));
            if (i != 0) {
                lp.leftMargin = DensityUtil.dip2px(MainActivity.this, 7);
            }
            iv.setLayoutParams(lp);
            iv.setBackgroundResource(R.drawable.xml_round_orange_grey_sel);
            iv.setEnabled(false);
            if (i == 0) {
                iv.setEnabled(true);
            }
            llIndexContainer.addView(iv);
        }
    }
    // 为ViewPager设置监听器
    private void refreshPoint(int position) {
        if (llIndexContainer != null) {
            for (int i = 0; i < llIndexContainer.getChildCount(); i++) {
                llIndexContainer.getChildAt(i).setEnabled(false);
                if (i == position) {
                    llIndexContainer.getChildAt(i).setEnabled(true);
                }
            }
        }
    }
}

主activity的布局为

.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    .support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">
        "@+id/rel"
            app:layout_scrollFlags="scroll"
            android:layout_width="match_parent"
            android:layout_height="180dp">
            .support.v4.view.ViewPager
                android:background="#91deca"
                android:id="@+id/vp_shuffling"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            "@+id/ll_index_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:background="@drawable/home_banner_index_mask"
                android:gravity="center_horizontal"
                android:orientation="horizontal"
                android:paddingBottom="5dp"
                android:paddingTop="5dp"/>
        
        .support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#91deca"
            app:tabGravity="fill"
            app:tabMode="fixed"
            app:tabSelectedTextColor="#ff0000"
            app:tabTextColor="#ffffff" />
    .support.design.widget.AppBarLayout>

    "match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scrollbars="none"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
        .support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    

.support.design.widget.CoordinatorLayout>

fragment的布局为

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
   .support.v4.widget.SwipeRefreshLayout
       android:id="@+id/refresh_layout"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
   <com.lyx.demo.view.LoadMoreRecyclerView
       android:id="@+id/recycler_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:scrollbars="none" />
.support.v4.widget.SwipeRefreshLayout>

点击去往csdn下载源码

点击去往github下载源码

如有任何疑问欢迎留言

你可能感兴趣的:(android)