[英]How to anchor simple button to snackbar
我有按鈕而不是浮動動作按鈕,我想用快餐欄將其錨定,因為它用浮動動作欄進行錨定,例如顯示小吃欄時浮動動作按鈕向上移動,對於浮動動作條,我們這樣做:
Snackbar.make(fab, s, Snackbar.LENGTH_SHORT);
我如何使用簡單的按鈕做為點心欄和按鈕,不知道點心欄的存在,反之亦然,而是獨立移動
謝謝
Docs這樣說
在視圖層次結構中具有CoordinatorLayout可使Snackbar啟用某些功能,例如滑動到關閉以及自動移動FloatingActionButton之類的小部件。
因此,只要您的按鈕位於協調器布局的正下方,您就可以像這樣將按鈕傳遞給Snackbar
Snackbar.make(yourButton, s, Snackbar.LENGTH_SHORT);
。 小部件向上移動應該可以。
您必須將“ Behavior
附加到要隨Snakebar
移動一起移動的View
在這里,我創建一個自定義View
,並將行為附加到該View
@CoordinatorLayout.DefaultBehavior(CustomView.Behavior.class)
public class CustomView extends View {
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public static class Behavior extends CoordinatorLayout.Behavior<CustomView> {
public Behavior() {
super();
}
public Behavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onAttachedToLayoutParams(@NonNull CoordinatorLayout.LayoutParams lp) {
if (lp.dodgeInsetEdges == Gravity.NO_GRAVITY) {
// This setting makes it works (learn from FloatingActionButton.Behavior)
lp.dodgeInsetEdges = Gravity.BOTTOM;
}
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, CustomView child,
View dependency) {
return false;
}
}
}
在您的布局中使用此CustomView
,它應該可以工作
FloatingActionButton
具有相同的功能,它具有內部Behavior
,該Behavior
基於AppBarLayout
運動對陰影填充,顯示/隱藏進行AppBarLayout
。 CoordinatorLayout
每個移動都基於其Behavior
機制
在這里引用: http : //saulmm.github.io/mastering-coordinator
P / S :關於Snakebar.make
用法,將CoordinatorLayout
傳遞給view
參數,不要傳遞任何其他組件,這將節省系統性能。 如果您查看Snakebar
代碼,它就有一個循環,並使用view參數查找根視圖。 根視圖就是它想要的:
private static ViewGroup findSuitableParent(View view) {
ViewGroup fallback = null;
do {
if (view instanceof CoordinatorLayout) {
// We've found a CoordinatorLayout, use it
return (ViewGroup) view;
} else if (view instanceof FrameLayout) {
if (view.getId() == android.R.id.content) {
// If we've hit the decor content view, then we didn't find a CoL in the
// hierarchy, so use it.
return (ViewGroup) view;
} else {
// It's not the content view but we'll use it as our fallback
fallback = (ViewGroup) view;
}
}
if (view != null) {
// Else, we will loop and crawl up the view hierarchy and try to find a parent
final ViewParent parent = view.getParent();
view = parent instanceof View ? (View) parent : null;
}
} while (view != null);
// If we reach here then we didn't find a CoL or a suitable content view so we'll fallback
return fallback;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.