在Android中,Snackbar的确没有提供直接设置锚点(anchor)的方法。不过,可以通过以下解决方法来实现在Snackbar上设置锚点:
CoordinatorLayout coordinatorLayout = findViewById(R.id.coordinatorLayout);
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Snackbar with Anchor View", Snackbar.LENGTH_LONG);
View anchorView = findViewById(R.id.anchorView);
snackbar.getView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
snackbar.setAnchorView(anchorView);
snackbar.getView().removeOnLayoutChangeListener(this);
}
});
snackbar.show();
public class CustomSnackbar {
public static Snackbar make(View view, CharSequence text, int duration) {
Snackbar snackbar = Snackbar.make(view, text, duration);
return snackbar;
}
public static void setAnchorView(Snackbar snackbar, View anchorView) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) snackbar.getView().getLayoutParams();
params.anchorGravity = Gravity.TOP;
params.gravity = Gravity.TOP;
params.anchorId = anchorView.getId();
snackbar.getView().setLayoutParams(params);
}
}
然后,在你的代码中,使用CustomSnackbar类来创建Snackbar,并调用setAnchorView()方法来设置锚点。以下是示例代码:
View anchorView = findViewById(R.id.anchorView);
Snackbar snackbar = CustomSnackbar.make(coordinatorLayout, "Snackbar with Anchor View", Snackbar.LENGTH_LONG);
CustomSnackbar.setAnchorView(snackbar, anchorView);
snackbar.show();
通过以上两种方法,你可以在Snackbar上设置锚点。记得根据你的布局文件和需求选择适合你的解决方法。