android Material Design之 ToolBar+TabLayout+recycleView的效果实现

本文的代码参考自githup上的源码  地址:https://github.com/git0pen/AndroidNewWidgetsDemo.git  源码里有侧滑,浮动按钮等控件, 我只针对ToolBar+TabLayout的控件实现做一个介绍,要想了解全部的可去下载源码

开发软件:Android studio

需要在grade文件中加上 compile 'com.android.support:design:22.2.0'   compile 'com.android.support:recyclerview-v7:22.2.0'  这两句话 

ok,现在开始代码编写

MainActivity

public class MainActivity extends AppCompatActivity{


    private AppBarLayout mAppBarLayout;   //用来控制上滑隐藏ToolBar的控件
    private Toolbar mToolbar;

    //TabLayout+ViewPager实现页面滑动展示多样化的adapter
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    //设定TabLayout中的tab标题
    private String[] mTitles=new String[]{"listView布局","GridView布局","瀑布流布局","流布局"};

    //填充到ViewPager中的Fragment
    private List mFragments;

    //ViewPager的数据适配器
    private MyViewPagerAdapter mMyViewPagerAdapter;

    //定义一个变量 监测到ViewPager滑动到哪一个Fragment
     private String type="type";


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

        //初始化各种控件
        initView();
        //初始化mFragments  为mFragmens填充Fragment
        initData();

        //对各种控件进行设置,适配,填充数据
        configViews();
    }

    private void configViews() {

        //设置显示ToolBar
        setSupportActionBar(mToolbar);

        // 初始化ViewPager的适配器,并设置给它

        mMyViewPagerAdapter=new MyViewPagerAdapter(getSupportFragmentManager(),mTitles,mFragments);
        mViewPager.setAdapter(mMyViewPagerAdapter);
        //设置ViewPager最大缓存的页面个数
        mViewPager.setOffscreenPageLimit(5);
        // 给ViewPager添加页面动态监听器(为了让Toolbar中的Title可以变化相应的Tab的标题)
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                 mToolbar.setTitle(mTitles[position]);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        // 将TabLayout和ViewPager进行关联,让两者联动起来
        mTabLayout.setupWithViewPager(mViewPager);

        // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
        mTabLayout.setTabsFromPagerAdapter(mMyViewPagerAdapter);
    }

    private void initData() {

        mFragments=new ArrayList<>();
        for(int i=0; i<mTitles.length;i++){
            Bundle mBundle=new Bundle();
            mBundle.putInt(type,i);
            MyFragment myFragment=new MyFragment();
            myFragment.setArguments(mBundle);
            mFragments.add(i,myFragment);

        }
    }

    private void initView() {
        mAppBarLayout= (AppBarLayout) findViewById(R.id.wx_appBarLayout);
        mToolbar= (Toolbar) findViewById(R.id.wx_toolBar);
        mTabLayout= (TabLayout) findViewById(R.id.wx_tablayout);
        mViewPager= (ViewPager) findViewById(R.id.wx_viewpager);
    }

}


MyFragment

public class MyFragment extends Fragment implements MyRecycleViewAdapter.OnItemClickListener{


    private View mView;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private MyRecycleViewAdapter mMyRecycleViewAdapter;
    private MyStaggeredAdapter mMyStaggeredAdapter;


    private static final int VERTICAL_LIST=0;
    private static final int VERTICAL_GRID=1;
    private static final int STAGGERED_GRID=2;
    private  int type=0;
    private  int SPAN_NUMBER=5;  //用来决定GridView一行显示几个


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //返回Fragment的视图 具体可以上网查看这个类的方法
        mView=inflater.inflate(R.layout.fragment_main,container,false);

        return mView;
    }


    //这个方法是在onCreateView()后执行,具体可查看Fragment的生命周期
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRecyclerView= (RecyclerView) mView.findViewById(R.id.wx_recycleView);
        type= (int) getArguments().get("type");

        switch (type){

            case VERTICAL_LIST:

                mLayoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
                break;

            case VERTICAL_GRID:
                mLayoutManager=new GridLayoutManager(getActivity(),SPAN_NUMBER,GridLayoutManager.VERTICAL,false);
                break;

            case STAGGERED_GRID:   //瀑布流
                mLayoutManager=new StaggeredGridLayoutManager(SPAN_NUMBER,GridLayoutManager.VERTICAL);
                break;
        }
        if(type!=STAGGERED_GRID){
            mMyRecycleViewAdapter=new MyRecycleViewAdapter(getActivity());
            mMyRecycleViewAdapter.setOnItemClickListener(this);
            mRecyclerView.setAdapter(mMyRecycleViewAdapter);
        }else{
            mMyStaggeredAdapter=new MyStaggeredAdapter(getActivity());
            mRecyclerView.setAdapter(mMyStaggeredAdapter);
        }
        mRecyclerView.setLayoutManager(mLayoutManager);
    }

    //点击事件
    @Override
    public void onItemClickListener(View view, int position) {
        Toast.makeText(getActivity(), "单击事件", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemLongClick(View view, int position) {
        Toast.makeText(getActivity(), "长按事件", Toast.LENGTH_SHORT).show();
    }
}

MyRecyCleViewAdapter

/**
 * Created by Administrator on 2015/11/12.
 * RecycleView的具体用法可上网搜 很多
 */
public class MyRecycleViewAdapter extends RecyclerView.Adapter {

     //RecycleView 并没有提供监听方法 所以需要我们自定义一个接口

    public interface OnItemClickListener{

         void onItemClickListener(View view,int position);
         void onItemLongClick(View view, int position);
    }
    public OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener listener){
        this.mOnItemClickListener=listener;
    }

    public Context mContext;
    public List mDatas;

    public MyRecycleViewAdapter(Context mContext) {

        this.mContext = mContext;
        mDatas = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            mDatas.add(i + "");
        }
    }


    /**
     * 创建一个视图 ViewHolder
     */
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View mView = LayoutInflater.from(mContext).inflate(R.layout.item_main, viewGroup, false);
        return new MyViewHolder(mView);
    }

    /**
     * 填充数据
     */
    @Override
    public void onBindViewHolder(final MyViewHolder myViewHolder, final int position) {

        if(mOnItemClickListener!=null){
            myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnItemClickListener.onItemClickListener(myViewHolder.itemView, position);

                }
            });

            myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mOnItemClickListener.onItemLongClick(myViewHolder.itemView, position);
                    return true;
                }
            });
        }
        myViewHolder.btn.setText(mDatas.get(position));
    }

    /**
     * 返回集合大小
     */
    @Override
    public int getItemCount() {
        return mDatas.size();
    }
}

MyStaggeredAdapter  

/**
 * Created by Administrator on 2015/11/13.
 */
public class MyStaggeredAdapter extends RecyclerView.Adapter{

    public Context mContext;
    public List mDatas;
    public List mHeights;

    public MyStaggeredAdapter(Context mContext){
        this.mContext=mContext;
        mDatas=new ArrayList<>();
        mHeights=new ArrayList<>();

        for(int i=0;i<50;i++){
            mDatas.add(i+"");
        }
        for(int i=0;i<mDatas.size();i++){
            mHeights.add((int) (Math.random()*300)+200);
        }
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(mContext).inflate(R.layout.item_main, parent, false);

        return new MyViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        ViewGroup.LayoutParams mLayoutParams=holder.btn.getLayoutParams();
        mLayoutParams.height=mHeights.get(position);
        holder.btn.setLayoutParams(mLayoutParams);
        holder.btn.setText(mDatas.get(position));
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

MyViewHolder

/**
 * Created by Administrator on 2015/11/12.
 */
public class MyViewHolder extends RecyclerView.ViewHolder{
        public Button btn;
        public MyViewHolder(View itemView) {
            super(itemView);
            btn= (Button) itemView.findViewById(R.id.wx_btn);
        }
    }

MyViewPageAdapter

/**
 * Created by Administrator on 2015/11/12.
 */
public class MyViewPagerAdapter extends FragmentStatePagerAdapter{

    private String[] mTitles;
    private List mFragments;

    public MyViewPagerAdapter(FragmentManager fm,String[] mTitles,List mFragments) {
        super(fm);
        this.mTitles=mTitles;
        this.mFragments=mFragments;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }
}

xml 代码

activity.main

    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="match_parent"
    android:orientation="vertical"
    >

            android:id="@+id/wx_appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
                    android:id="@+id/wx_toolBar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"  
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            />
                    android:id="@+id/wx_tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabTextColor="#dfd415dd"
            app:tabIndicatorColor="@color/main_white" />

        

            android:id="@+id/wx_viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


  这一行代码是用来控制ViewPager上滑,下滑时ToolBar隐藏和显示

app:layout_scrollFlags="scroll|enterAlways"  
fragment.main
xml version="1.0" encoding="utf-8"?>
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

            android:id="@+id/wx_recycleView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


item_main
xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical">


    

基本的解释在文中已写上备注,要是有不懂的可上网查当前类,即可了解 ,本人也是正处于学习阶段,如果有不对的地方,请交流,谢谢

你可能感兴趣的:(android,布局,android,tabLayout)