在檢視之間建立依賴關係
你可以使用 CoordinatorLayout.Behavior 在檢視之間建立依賴關係。你可以通過以下方式將 View 錨定到另一個 View:
- 使用
layout_anchor屬性。 - 建立一個自定義
Behavior並實現layoutDependsOn方法返回true。
例如,為了建立 Behavior 以在移動另一個時移動 ImageView(示例工具欄),請執行以下步驟:
-
建立自定義行為 :
public class MyBehavior extends CoordinatorLayout.Behavior<ImageView> {...} -
重寫
layoutDependsOn方法返回true。每次佈局發生更改時都會呼叫此方法:@Override public boolean layoutDependsOn(CoordinatorLayout parent, ImageView child, View dependency) { // Returns true to add a dependency. return dependency instanceof Toolbar; } -
每當方法
layoutDependsOn返回true時,方法onDependentViewChanged被呼叫:@Override public boolean onDependentViewChanged(CoordinatorLayout parent, ImageView child, View dependency) { // Implement here animations, translations, or movements; always related to the provided dependency. float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight()); child.setTranslationY(translationY); }