Android學習系列Toolbar,AppBarLayout,CoordinatorLayout,CollapsingToolbarLayout使用小結

隔壁小王 8年前發布 | 47K 次閱讀 Android開發 移動開發

上面幾個控件,相信大家已經耳熟能詳,是基于MD風格的Android Design Support Library里面所包含的控件。

添加依賴:

 compile 'com.android.support:design:23.4.0'

Toolbar小結

使用Toolbar,首先要關閉actionbar。

方法1:

使得Activity的主題繼承Theme.AppCompat.NoActionBar

方法2:

 <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

然后在清單文件中的application 添加 android:theme=”@style/AppTheme”即可

布局:

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?colorPrimary"/>

使用actionBarSize默認高度,以及colorPrimary作為背景色,可自選。

使用:

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        // App Logo
        toolbar.setLogo(R.mipmap.ic_launcher);
        // Title
        toolbar.setTitle("My Title");
        // Sub Title
        toolbar.setSubtitle("Sub title");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_launcher);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);

setNavigationIcon,setOnMenuItemClickListener必須放在setSupportActionBar之后才有效果,setLogo,setSubtitle,setTitle,必須放在setSupportActionBar之前才有效果。

這里寫圖片描述

menu點擊:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            String msg = "";
            switch (menuItem.getItemId()) {
                case R.id.action_edit:
                    msg += "Click edit";
                    break;
                case R.id.action_share:
                    msg += "Click share";
                    break;
                case R.id.action_settings:
                    msg += "Click setting";
                    break;
            }

            if(!msg.equals("")) {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    };

AppBarLayout小結:

AppBarLayout是一個垂直方向的linearLayout,包含了對滑動手勢的處理。我們可以使用app:layout_scrollFlags這樣的標簽來設置滑動的行為表現。

使用AppBarLayout需要注意下面幾個要點:

首先,AppBarLayout必須作為CoordinatorLayout的直接子View
其次,在AppBarLayout里面必須包含一個ToolBar
最后,在CoordinatorLayout里面可以添加那些可以滑動的組件,例如RecyclerView

布局結構:

   <!--必須使用CoordinatorLayout才會有向上隱藏效果-->
    <android.support.design.widget.CoordinatorLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar_layout"
            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/tool_bar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways" />

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="35dp"
                android:background="#03BCD4"/>

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

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

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

解析:
一:因為包含toolBar
android:theme=”@style/ThemeOverlay.AppCompat.Dark.ActionBar”

二: 設置滑動隱藏
app:layout_scrollFlags=”scroll|enterAlways”

enterAlways:
一旦向上滾動這個view就可見。
enterAlwaysCollapsed:
顧名思義,這個flag定義的是何時進入(已經消失之后何時再次顯示)。假設你定義了一個最小高度(minHeight)同時enterAlways也定義了,那么view將在到達這個最小高度的時候開始顯示,并且從這個時候開始慢慢展開,當滾動到頂部的時候展開完。
exitUntilCollapsed:
同樣顧名思義,這個flag時定義何時退出,當你定義了一個minHeight,這個view將在滾動到達這個最小高度的時候消失。

三:滑動組件的動畫,滿一屏才有效果
app:layout_behavior=”@string/appbar_scrolling_view_behavior”

效果:
滑動隱藏AppBarLayout

這里寫圖片描述

這里寫圖片描述

CoordinatorLayout小結:

CoordinatorLayout繼承自framelayout,我們相當于在framelayout上做一些操作

添加Floating Action Button:

<android.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/main_content" android:layout_width="match_parent" android:layout_height="match_parent">
    <!--其他布局-->
   <android.support.design.widget.FloatingActionButton  android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="15dp" android:src="@mipmap/ic_launcher" app:backgroundTint="@color/colorPrimary"/>
        </android.support.design.widget.CoordinatorLayout>

app:backgroundTint設置背景顏色

效果:
這里寫圖片描述

FloatingActionButton隨著Recylerview的滑動顯示和隱藏:

方法一:
監聽recylerview或者scrollview的滑動事件,判斷是上滑還是下滑,
1:定義變量private int mScrollThreshold=0;
2:監聽滑動

recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                boolean isSignificantDelta = Math.abs(dy) > mScrollThreshold;
                if (isSignificantDelta) {
                    if (dy > 0) {
                        fab.hide();
                    } else {
                        fab.show();
                    }
                }
                mScrollThreshold = dy;

            }
        });

這是比較容易理解,比較容易實現的方法。

方法二:
自定義ScrollAwareFABBehaviorDefault:

/** * Created by Administrator on 2016/6/12. */
public class ScrollAwareFABBehaviorDefault extends FloatingActionButton.Behavior {

    public ScrollAwareFABBehaviorDefault(Context context, AttributeSet attrs) {
        super();
    }

    @Override
    public boolean onStartNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
                                       final View directTargetChild, final View target, final int nestedScrollAxes) {
        // Ensure we react to vertical scrolling
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
                || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
    }

    @Override
    public void onNestedScroll(final CoordinatorLayout coordinatorLayout, final FloatingActionButton child,
                               final View target, final int dxConsumed, final int dyConsumed,
                               final int dxUnconsumed, final int dyUnconsumed) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
        if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
            // User scrolled down and the FAB is currently visible -> hide the FAB
            child.hide();
        } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
            // User scrolled up and the FAB is currently not visible -> show the FAB
            child.show();
        }
    }
}

在布局中引用:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="15dp"
        android:src="@mipmap/ic_launcher"
        app:backgroundTint="@color/colorPrimary"
        app:layout_behavior="com.example.com.testtoolbar.ScrollAwareFABBehaviorDefault" />/>

其他方式借鑒:
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2016/0407/4126.html

CollapsingToolbarLayout

CollapsingToolbarLayout能讓我們做出更高級的動畫,比如在里面放一個ImageView,然后在它折疊的時候漸漸淡出。同時在用戶滾動的時候title的高度也會隨著改變。

效果實例:
這里寫圖片描述

布局結構:

<android.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/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginStart="48dp"
            app:expandedTitleMarginEnd="64dp">

            <ImageView
                android:id="@+id/back_drop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/title"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/tool_bar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin" />

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

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

解析:

app:layout_collapseMode=”pin”來確保Toolbar在view折疊的時
候仍然被固定在屏幕的頂部。使用app:layout_collapseMode=”parallax”(以及使用
app:layout_collapseParallaxMultiplier=”0.7″來設置視差因子)來實現視差滾動效果(比如
CollapsingToolbarLayout里面的一個ImageView),這中情況和CollapsingToolbarLayout的
app:contentScrim=”?attr/colorPrimary”屬性一起配合更完美。

Java設置:

CollapsingToolbarLayout collapsingToolbar =(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle("詳情界面");

解析:當你讓CollapsingToolbarLayout和Toolbar在一起使用的時候,title會在展開的時候自動變得 大些,而在折疊的時候讓字體過渡到默認值。必須注意,在這種情況下你必須在CollapsingToolbarLayout上調用setTitle(), 而不是在Toolbar上。

 

來自: http://blog.csdn.net/qq_16131393/article/details/51647388

 本文由用戶 隔壁小王 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!