CoordinatorLayout的使用(一)——簡單使用

簡介

CoordinatorLayout是Android support design推出的新佈局,主要用於作爲視圖根佈局以及協調子控件的行爲(根據用戶的觸摸行爲產生一定的動畫效果)。主要是通過設置子View的 Behaviors來實現不同效果。

環境配置

直接在Module的build.gradle文件引入


懸浮按鈕FloatingActionButton的使用

這個使用比較簡單,直接在XML中通過CoordinatorLayout作爲父佈局,嵌套FloatingActionButton即可
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.victor.coordinatorlayoutdemo.MainActivity">
	<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="20dp"
        app:backgroundTint="@color/colorPrimary"
        android:src="@android:drawable/ic_dialog_email"/>

</android.support.design.widget.CoordinatorLayout>
幾個比較關鍵的屬性(注意區分android和app自定義屬性,使用混了會報錯,後面幾個列子也一樣):
layout_gravity:控制自己位於父控件的位置
app:backgroundTint:控制背景顏色
android:src:和Image的src一樣
layout_anchor:設置錨點(參考的控件)
layout_anchorGravity:相對於錨點的位置bottom/end……等屬性
顯示效果(右下角就能顯示了):


AppBarLayout的使用

AppBarLayout本身一般沒有太多直接的UI展示的效果,一般是通過和CollapsingToolbarLayout和TabLayout進行嵌套使用。

嵌套TabLayout使用

通過TabLayout的嵌套使用,就可以通過滾動來控制ToolBar的顯示和隱藏了。
佈局文件:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 android:orientation="vertical">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/tb_main"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/blue"
            app:tabIndicatorColor="@color/white"
            app:tabSelectedTextColor="@android:color/holo_red_light"
            app:tabTextColor="@color/white"/>

    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/vp_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

java代碼實現
package com.victor.coordinatorlayoutdemo;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import com.victor.coordinatorlayoutdemo.fragment.FoundFragment;
import com.victor.coordinatorlayoutdemo.fragment.FriendFragment;
import com.victor.coordinatorlayoutdemo.fragment.MsgFragment;

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

public class MainActivity extends AppCompatActivity {


    private List<Fragment> mFragments;
    private String[] mTabTitles = {"消息", "好友", "動態"};

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

        ViewPager viewPager = (ViewPager) findViewById(R.id.vp_main);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_main);

        // 初始化Adapter
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), this);
        // 設置adapter將ViewPager和Fragment關聯起來
        viewPager.setAdapter(adapter);
        // 將TabLayout和ViewPager關聯,達到TabLayout和Viewpager、Fragment聯動的效果
        tabLayout.setupWithViewPager(viewPager);

    }

    /**
     * 初始化toolBar
     */
    private void initToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.tb_main);
        // 指定ToolBar的標題
        toolbar.setTitle("CoordinatorLayout");
        // 將toolBar和actionBar進行關聯
        setSupportActionBar(toolbar);
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        MsgFragment msgFragment = new MsgFragment();
        FriendFragment friendFragment = new FriendFragment();
        FoundFragment foundFragment = new FoundFragment();
        // 將三個fragment放入List裏面管理,方便使用
        mFragments = new ArrayList<>();
        mFragments.add(msgFragment);
        mFragments.add(friendFragment);
        mFragments.add(foundFragment);
    }


    class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private Context context;

        public MyFragmentPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int position) {
            // 獲取指定位置的Fragment對象
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            // ViewPager管理頁面的數量
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // 設置indicator的標題(TabLayout中tab的標題)
            return mTabTitles[position];
        }
    }

}

由於這裏重點不在TabLayout的使用上,對於tabLayout結合VeiwPager的使用請看代碼裏面的註釋。這裏通過滑動控制的ToolBar的關鍵就是app:layout_scrollFlags屬性,該屬性有一下幾個值可以設置:
scroll: 設置這個flag後就會隨着滑動而滾出屏幕, 沒有設置這個flag的view將被固定在屏幕頂部。上述列子中的TabLayout 沒有設置這個值,最終停留在屏幕頂部。
enterAlways: 設置這個flag時,向下的滾動都會導致該view變爲可見,啓用快速“返回模式”。
enterAlwaysCollapsed: 當你的視圖已經設置最小高度屬性(minHeight)再設置該屬性,那麼你的視圖只能以最小高度進入,僅當滾動視圖到達頂部時才擴大到完整高度。
exitUntilCollapsed: 從大慢慢滾動變小,最後摺疊在頂端。
這裏需要注意的是:滾動控件必須實現NestedScrollingChild接口(如RecyclerView,NestedScrollView),而沒有實現該接口的滾動控件如ScrollView、WebView、ListView是全部都沒有作用的。後面CollapsingToolbarLayout也同樣遵循該規則。
效果如下:

嵌套CollapsingToolbarLayout使用

和CollapsingToolbarLayout嵌套使用,可以達到展示和摺疊toolBar的效果,一般在詳情頁,博客,動態等頁面使用比較多。這裏的列子使用RecyclerView作爲數據展示控件。
佈局文件如下:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.victor.coordinatorlayoutdemo.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="350dp">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/ctl_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:expandedTitleGravity="end|bottom"
            app:expandedTitleMarginEnd="15dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="#FF078CDF">
            
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@mipmap/ctl_bg"/>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="parallax"></android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="20dp"
        app:backgroundTint="@color/colorPrimary"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchorGravity=""
        />

</android.support.design.widget.CoordinatorLayout>

Java代碼
package com.victor.coordinatorlayoutdemo;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CollapsingActivity extends AppCompatActivity {

    // 模仿RecyclerView的數據
    String[] mDatas = {"Each of us holds a unique place in the world. You are special,no matter what others say or what you may think. So forget about being replaced. You can’t be.",
            "How beautiful it was, falling so silently, all day long, all night long, on the mountains, on the meadows, on the roofs of the living, on the graves1) of the dead!",
            "All white save the river, that marked2) its course by a winding black line across the landscape3), and the leafless trees, that against the leaden4) sky now revealed more fully the wonderful beauty and intricacy5) of their branches!",
            "What silence, too, came with the snow, and what seclusion6)! Every sound was muffled7); every noise changed to something soft and musical.",
            "In the entire world there's nobody like me. Since the beginning of time, there has never been another person like me. Nobody has my smile. Nobody has my eyes, my nose, my hair, my hands, or my voice.",
            "If you give up when it's winter, you will miss the promise of your spring, the beauty of your summer, fulfillment of your fall. Don't let the pain of one season destroy the joy of all the rest.",
            "A burning desire is the starting point of all accomplishment. Just like a small fire cannot give much heat, a weak desire cannot produce great results.",
            "I have drunk the cup of life down to its very dregs7). They have only sipped the bubbles on top of it. I know things they will never know. I see things to which they are blind.",
            "It is only the women whose eyes have been washed clear with tears who get the broad vision that makes them little sisters to all the world."};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collapsing);
        initToolBar();
        CollapsingToolbarLayout ctlLayout = (CollapsingToolbarLayout) findViewById(R.id.ctl_layout);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv);
        ctlLayout.setTitle("Victor");
        ctlLayout.setExpandedTitleColor(Color.WHITE);
        ctlLayout.setCollapsedTitleTextColor(Color.YELLOW);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(new MyAdapter());
    }

    private void initToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(getApplicationContext(), R.layout.list_item, null);
            MyViewHolder viewHolder = new MyViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.mTextView.setText(mDatas[position]);
        }

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

    class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView mTextView;

        public MyViewHolder(View itemView) {
            super(itemView);
            mTextView = (TextView) itemView.findViewById(R.id.tv_item);
        }
    }
}

幾個比較關鍵的屬性:
app:expandedTitleMarginStart:設置展開後標題的邊距,除了expandedTitleMarginStart,還有expandedTitleMarginEnd等等,除了設置邊距還能設置顏色等等
app:contentScrim:滾動的顏色
app:title:toolBar標題
app:statusBarScrim:狀態欄的背景
app:layout_collapseMode:設置滾動模式(一般是在它的子View裏面設置)
上面很多屬性也可以通過java代碼的形式進行設置。類似TextView的setText()等方法。
其中有些屬性根據自己喜好設置,但是 AppBarLayout的高度最好固定,CollapsingToolbarLayout的子視圖設置layout_collapseMode屬性一定要設置。
展示效果:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章