一领虹、簡介
CoordinatorLayout
翻譯為協(xié)調者布局届宠,是在 Google IO/15 大會發(fā)布的赐写,是用來協(xié)調其子View們之間動作的一個容器鸟蜡,遵循Material Design風格,包含在 com.android.support:design
中血淌。CoordinatorLayout
是一個超級強大的FrameLayout
矩欠,結合AppBarLayout
、 CollapsingToolbarLayout
等可產生各種炫酷的效果悠夯。
二癌淮、使用
在項目的build.gradle引入material design庫
老版本(項目未遷移至AndroidX):
implementation 'com.android.support:design:28.0.0'
新版本(項目已遷移至AndroidX),本文使用:
implementation 'com.google.android.material:material:1.1.0'
1沦补、CoordinatorLayout結合AppBarLayout 使用
效果圖:
布局文件使用:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#222222"
android:gravity="center"
android:text="該區(qū)域可折疊"
android:textColor="@android:color/white"
android:textSize="30sp"
app:layout_scrollFlags="scroll" />
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#DD012D"
android:gravity="center"
android:text="該區(qū)域為上滑至頭部固定區(qū)域"
android:textColor="@android:color/white"
android:textSize="20sp" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/rv_demo1_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:layout_width="match_parent"
android:text="這是一個滾動布局"
android:textSize="200sp"
android:background="#00ff00"
android:layout_height="wrap_content"/>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
說明:
CoordinatorLayout
須要作為頂層父View乳蓄,子View想要與CoordinatorLayout
實現(xiàn)"聯(lián)動性"效果的首要條件是這個View必須實現(xiàn)了NestedScrollingChild
接口(例如:NestedScrollView
、RecyclerView
等控件)夕膀。CoordinatorLayout
子控件如果需要聯(lián)動虚倒,需要設置app:layout_behavior
屬性,上面AppBarLayout
沒有設置是因為本身有個默認的app:layout_behavior查看源碼如下:
public class AppBarLayout extends LinearLayout implements CoordinatorLayout.AttachedBehavior {
//...
}
2产舞、AppBarLayout中ScrollFlags值
XML使用app:layout_scrollFlags
設置魂奥,代碼中獲取該控件AppBarLayout.LayoutParams
再使用setScrollFlags(int)
設置
XML設置方法:
app:layout_scrollFlags="scroll|enterAlways"
代碼中設置方法:
TextView text= ... //確保該View是被AppBarLayout包裹的
AppBarLayout.LayoutParams params =
(AppBarLayout.LayoutParams) text.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
| AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
幾種設置效果如下:
- scroll (SCROLL_FLAG_SCROLL)
視圖將與滾動事件直接相關。需要設置此標志才能使任何其他標志生效易猫。如果此視圖之前的任何同級視圖沒有此標志耻煤,則此值無效。
app:layout_scrollFlags="scroll"
- enterAlways (SCROLL_FLAG_ENTER_ALWAYS)
當進入(在屏幕上滾動)時准颓,視圖將在任何向下滾動事件上滾動哈蝇,無論滾動視圖是否也在滾動。這通常被稱為“快速推出”模式攘已。
app:layout_scrollFlags="scroll|enterAlways"
- enterAlwaysCollapsed (SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED)
“enterAlways”的另一個標志炮赦,它將返回的視圖修改為僅在最初滾動回其折疊高度。一旦滾動視圖到達其滾動范圍的末尾样勃,此視圖的其余部分將滾動到視圖中吠勘。折疊高度由視圖的最小高度定義性芬。
android:minHeight="30dip"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
- exitUntilCollapsed (SCROLL_FLAG_EXIT_UNTIL_COLLAPSED)
退出時(從屏幕上滾動),視圖將滾動到“折疊”為止看幼。折疊高度由視圖的最小高度定義批旺。
android:minHeight="30dip"
app:layout_scrollFlags="scroll|exitUntilCollapsed" />
- snap (SCROLL_FLAG_SNAP)
在滾動結束時,如果視圖僅部分可見诵姜,則它將被捕捉并滾動到最近的邊。例如搏熄,如果視圖只顯示其底部的25%棚唆,則它將完全從屏幕上滾下。相反心例,如果它的底部75%是可見的宵凌,那么它將完全滾動到視圖中。
app:layout_scrollFlags="scroll|snap"
3止后、結合 CollapsingToolbarLayout 使用
效果圖:
布局文件:
<androidx.coordinatorlayout.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:fitsSystemWindows="true"
android:layout_height="match_parent"
>
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="#ff0000"
app:collapsedTitleGravity="center"
app:expandedTitleGravity="left|bottom"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:title="楊冪"
app:toolbarId="@+id/toolbar">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
app:srcCompat="@mipmap/ym" />
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_collapseMode="pin"
/>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/rv_demo1_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:layout_width="match_parent"
android:text="這是一個滾動布局"
android:textSize="200sp"
android:background="#00ff00"
android:layout_height="wrap_content"/>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
CollapsingToolbarLayout部分屬性
- app:contentScrim CollapsingToolbarLayout完全折疊后的背景顏色
- app:titleEnabled 是否顯示標題
- app:title 標題
- app:toolbarId toolbar 對應的view id
- app:statusBarScrim 折疊后狀態(tài)欄的背景
- app:scrimVisibleHeightTrigger 設置收起多少高度時瞎惫,顯示ContentScrim的內容
- app:scrimAnimationDuration 展開狀態(tài)和折疊狀態(tài)之間,內容轉換的動畫時間
- app:expandedTitleTextAppearance 布局張開的時候title的樣式
- app:expandedTitleMarginTop 布局張開的時候title的margin top
- app:expandedTitleMarginStart 布局張開的時候title的margin start
- app:expandedTitleMarginEnd 布局張開的時候title的margin end
- app:expandedTitleMarginBottom 布局張開的時候title的margin bottom
- app:expandedTitleMargin 布局張開的時候title的margin
- app:expandedTitleGravity 布局張開的時候title的位置
- app:collapsedTitleTextAppearance 布局折疊的時候title的樣式
- app:collapsedTitleGravity 布局折疊的時候title的gravity
4译株、CoordinatorLayout 中的 Behavior
Behavior行為控制器:實現(xiàn)了用戶可以在子視圖上進行的一個或多個交互瓜喇。這些交互可能包括拖動,滑動歉糜,甩動或任何其他手勢乘寒。
Behavior中常用的重寫的方法:
/**
* 確定使用Behavior的View要依賴的View的類型
* 只要是CoordinatorLayout內的View的狀態(tài)發(fā)送了變化,該方法就會執(zhí)行
* @param parent 頂層父控件CoordinatorLayout
* @param child 我們設置這個Behavior的View
* @param dependency 值會不斷的變化,他會輪詢CoordinatorLayout下所有所屬的子View
* @return 這里判斷dependency所屬的View是哪一個, 返回true,onDependentViewChanged才執(zhí)行,否則不執(zhí)行
*/
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency)
/**
* 當被依賴的View狀態(tài)改變時回調
* @param parent 頂層父控件CoordinatorLayout
* @param child 我們設置這個Behavior的View
* @param dependency 值會不斷的變化,他會輪詢CoordinatorLayout下所有所屬的子View
* @return 當我們改變了child的大小或者位置的時候我們需要返回true
*/
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency)
/**
* 當被依賴的View移除時回調
* @param parent 頂層父控件CoordinatorLayout
* @param child 我們設置這個Behavior的View
* @param dependency 值會不斷的變化,他會輪詢CoordinatorLayout下所有所屬的子View
*/
@Override
public void onDependentViewRemoved(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency)
簡單案例(向上滑動時底部控件漸漸隱藏匪补,向下滑動時底部控件漸漸顯示):
效果
自定義一個Behavior
public class Demo1Behavior extends CoordinatorLayout.Behavior<View> {
public Demo1Behavior() {
super();
}
public Demo1Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
//這里判斷dependency所屬的View是哪一個,返回true伞辛,onDependentViewChanged才執(zhí)行,否則不執(zhí)行
return dependency instanceof AppBarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
/*
*這里獲取dependency的top值,也就是AppBarLayout的top,因為AppBarLayout
*在是向上滾出界面的,我們的因為是和AppBarLayout相反,所以取絕對值.
*/
float translationY = Math.abs(dependency.getTop());
child.setTranslationY(translationY);
return true;
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#222222"
android:gravity="center"
android:text="該區(qū)域可折疊"
android:textColor="@android:color/white"
android:textSize="30sp"
app:layout_scrollFlags="scroll" />
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#DD012D"
android:gravity="center"
android:text="該區(qū)域為上滑至頭部固定區(qū)域"
android:textColor="@android:color/white"
android:textSize="20sp" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/rv_demo1_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:layout_width="match_parent"
android:text="這是一個滾動布局"
android:textSize="200sp"
android:background="#00ff00"
android:layout_height="wrap_content"/>
</androidx.core.widget.NestedScrollView>
//行為控制器引用 app:layout_behavior=".demo1.Demo1Behavior"
<TextView
android:layout_gravity="bottom"
app:layout_behavior=".demo1.Demo1Behavior"
android:layout_width="match_parent"
android:background="#ff00ff"
android:layout_height="50dip"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
三、案例
防招商銀行8.1全部菜單布局夯缺,上滑頂部區(qū)域隱藏蚤氏,導航條懸浮,點擊導航條可快速定位踊兜。
1竿滨、效果圖
2、布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".demo5.Demo5Activity">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/abl_demo5_content"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#222222"
android:gravity="center"
android:text="該區(qū)域可折疊"
android:textColor="@android:color/white"
android:textSize="30sp"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/tb_demo5_content"
android:layout_width="match_parent"
android:layout_height="50dip"
android:background="#ffffff">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_demo5_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
3润文、頁面代碼及數(shù)據適配器代碼
public class Demo5Activity extends AppCompatActivity {
private RecyclerView rv_demo5_content;
private List<Demo5Bean> data;
private TabLayout tb_demo5_content;
private AppBarLayout abl_demo5_content;
private GridLayoutManager gridLayoutManager;
private RecyclerView.SmoothScroller smoothScroller;
private List<Integer> titlePosition;
//是否正在滾動
private boolean isScroll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo5);
tb_demo5_content = findViewById(R.id.tb_demo5_content);
rv_demo5_content = findViewById(R.id.rv_demo5_content);
abl_demo5_content = findViewById(R.id.abl_demo5_content);
initData();
initTabLayout();
initRecyclerView();
}
private void initData() {
data = new ArrayList<Demo5Bean>();
titlePosition = new ArrayList<Integer>();
Demo5Bean bean = null;
for (int i = 0; i < 5; i++) {
bean = new Demo5Bean("標題" + i, Demo5Adapter.VIEW_TYPE_TITLE);
data.add(bean);
titlePosition.add(i + (i * 10));
for (int i1 = 0; i1 < 10; i1++) {
bean = new Demo5Bean(i + "_內容" + i1, Demo5Adapter.VIEW_TYPE_MENU);
data.add(bean);
}
}
}
private void initTabLayout() {
for (Demo5Bean datum : data) {
if (datum.getItemType() == Demo5Adapter.VIEW_TYPE_TITLE) {
tb_demo5_content.addTab(tb_demo5_content.newTab().setText(datum.getName()));
}
}
tb_demo5_content.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(!isScroll) {
//收縮折疊區(qū)
abl_demo5_content.setExpanded(false);
int tabPosition = tab.getPosition();
int titlePosition = getTitlePosition(tabPosition);
smoothScroller.setTargetPosition(titlePosition);
gridLayoutManager.startSmoothScroll(smoothScroller);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void initRecyclerView() {
gridLayoutManager = new GridLayoutManager(this, 4);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position < data.size()) {
Demo5Bean bean = data.get(position);
if (bean.getItemType() == Demo5Adapter.VIEW_TYPE_TITLE) {
//是標題則占4個item
return 4;
} else if (bean.getItemType() == Demo5Adapter.VIEW_TYPE_MENU) {
//是menu則正常占用一個item
return 1;
} else {
return 0;
}
} else {
//FooterView 占4個item
return 4;
}
}
});
//計算最后填充FooterView填充高度姐呐,全屏高度-狀態(tài)欄高度-tablayout的高度(這里固定高度50dp)-title標題高度(40)-最后分組高度(3排menu每個70),用于recyclerView的最后一個item FooterView填充高度
int screenH = getScreenHeight();
int statusBarH = getStatusBarHeight(this);
int tabH = dip2px(this,50);
int titleH = dip2px(this,40);
int lastMenusH= dip2px(this,70)*3;
int lastH = screenH - statusBarH - tabH -titleH-lastMenusH;
if(lastH<=0){
lastH=0;
}
Demo5Adapter mAdapter = new Demo5Adapter(data, this,lastH);
rv_demo5_content.setLayoutManager(gridLayoutManager);
rv_demo5_content.setAdapter(mAdapter);
//RecyclerView平滑Scroller
smoothScroller = new LinearSmoothScroller(this) {
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
@Nullable
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return gridLayoutManager.computeScrollVectorForPosition(targetPosition);
}
};
rv_demo5_content.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(newState==RecyclerView.SCROLL_STATE_IDLE){
isScroll=false;
}else{
isScroll=true;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
TabLayout.Tab tabAt = tb_demo5_content.getTabAt(getTabPosition(gridLayoutManager.findFirstVisibleItemPosition()));
if (tabAt != null && !tabAt.isSelected()) {
tabAt.select();
}
}
});
}
private int getTitlePosition(int tabPosition) {
//根據tabPosition找出TitlePosition
return titlePosition.get(tabPosition);
}
private int getTabPosition(int menuPosition) {
return titlePosition.indexOf(menuPosition);
}
private int getScreenHeight() {
return getResources().getDisplayMetrics().heightPixels;
}
public int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources()
.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
4典蝌、數(shù)據適配器
public class Demo5Adapter extends RecyclerView.Adapter {
public static final int VIEW_TYPE_TITLE = 0;
public static final int VIEW_TYPE_MENU = 1;
public static final int VIEW_TYPE_FOOTER = 2;
private final LayoutInflater inflater;
private List<Demo5Bean> data;
private Context context;
private int lastH;
public Demo5Adapter(List<Demo5Bean> data, Context context,int lastH) {
this.data = data;
this.context = context;
this.lastH = lastH;
inflater = LayoutInflater.from(context);
}
@Override
public int getItemViewType(int position) {
if (position == data.size()) {
return VIEW_TYPE_FOOTER;
} else {
Demo5Bean demo5Bean = data.get(position);
return demo5Bean.getItemType();
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case VIEW_TYPE_TITLE:
viewHolder = new Demo5TitleViewHolder(inflater.inflate(R.layout.itme_demo5_title, parent, false));
break;
case VIEW_TYPE_MENU:
viewHolder = new Demo5MenuViewHolder(inflater.inflate(R.layout.itme_demo5_menu, parent, false));
break;
case VIEW_TYPE_FOOTER:
View view = new View(parent.getContext());
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, lastH));
viewHolder = new Demo5FooterViewHolder(view);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_TITLE:
((Demo5TitleViewHolder) holder).tv_item_demo5_title.setText(data.get(position).getName());
Log.i("TTT",holder.itemView.getMeasuredHeight()+"VIEW_TYPE_TITLE");
break;
case VIEW_TYPE_MENU:
((Demo5MenuViewHolder) holder).tv_item_demo5_menu.setText(data.get(position).getName());
Log.i("TTT",holder.itemView.getMeasuredHeight()+"VIEW_TYPE_MENU");
break;
}
}
@Override
public int getItemCount() {
return data.size() + 1;
}
public static class Demo5TitleViewHolder extends RecyclerView.ViewHolder {
private final TextView tv_item_demo5_title;
public Demo5TitleViewHolder(@NonNull View itemView) {
super(itemView);
tv_item_demo5_title = itemView.findViewById(R.id.tv_item_demo5_title);
}
}
public static class Demo5MenuViewHolder extends RecyclerView.ViewHolder {
private final TextView tv_item_demo5_menu;
public Demo5MenuViewHolder(@NonNull View itemView) {
super(itemView);
tv_item_demo5_menu = itemView.findViewById(R.id.tv_item_demo5_menu);
}
}
public static class Demo5FooterViewHolder extends RecyclerView.ViewHolder {
public Demo5FooterViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
5曙砂、實體Bean
public class Demo5Bean {
private String name;
private int itemType;
public Demo5Bean(String name, int itemType) {
this.name = name;
this.itemType = itemType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getItemType() {
return itemType;
}
public void setItemType(int itemType) {
this.itemType = itemType;
}
}
6、其他說明
AppBarLayout代碼主動折疊與打開
//打開AppBarLayout
appBarLayout.setExpanded(true);
//關閉AppBarLayout
appBarLayout.setExpanded(false);
參考:https://blog.csdn.net/zping0808/article/details/104669944/