默认Snackbar支持底部或者顶部显示,不支持居中显示
查看Snackbar的源码可以看到createMarginLayoutParams方法中有位置的处理SnackbarPosition ,
针对不同的显示位置设置对应的params规则,这里我们将表示位置的枚举SnackbarPosition中添加一种类型PARENT_CENTER
public static enum SnackbarPosition { TOP(Gravity.TOP), BOTTOM(Gravity.BOTTOM), BOTTOM_CENTER(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL) , PARENT_CENTER(Gravity.CENTER_VERTICAL); }
createMarginLayoutParams方法中部分逻辑修改如下:
else if (viewGroup instanceof RelativeLayout) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height); if (position == SnackbarPosition.TOP) params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); else if(position == SnackbarPosition.BOTTOM) params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE); else if(position == SnackbarPosition.PARENT_CENTER) params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); return params; }
如果viewgGroup的类型不是ReletiveLayout,也可以不修改createMarginLayoutParams方法中的逻辑。
因为,提示条在中间显示默认位移的动画效果有些突兀,这里我们修改下居中显示时的动画效果,修改为透明度动画。
修改两个获取动画资源函数:
/** * @param snackbarPosition * @return the animation resource used by this {@link com.nispok.snackbar.Snackbar} instance * to enter the view */ @AnimRes public static int getInAnimationResource(SnackbarPosition snackbarPosition) { return snackbarPosition == SnackbarPosition.TOP ? R.anim.sb__top_in : (snackbarPosition == SnackbarPosition.PARENT_CENTER ? R.anim.sb__center_in : R.anim.sb__bottom_in); } /** * @param snackbarPosition * @return the animation resource used by this {@link com.nispok.snackbar.Snackbar} instance * to exit the view */ @AnimRes public static int getOutAnimationResource(SnackbarPosition snackbarPosition) { return snackbarPosition == SnackbarPosition.TOP ? R.anim.sb__top_out : (snackbarPosition == SnackbarPosition.PARENT_CENTER ? R.anim.sb__center_out : R.anim.sb__bottom_out); }
anim文件夹下增加sb__center_in sb__center_out两个配置文件如下:
sb__center_in.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:fromAlpha="0" android:interpolator="@interpolator/sb__decelerate_cubic" android:toAlpha="1" /> </set>
sb__center_out.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:fromAlpha="1" android:interpolator="@interpolator/sb__decelerate_cubic" android:toAlpha="0" /> </set>
在sample的示例代码SnackSampleActivity中单行显示文本的Snackbar的代码修改如下:
singleLineButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SnackbarManager.show( Snackbar.with(SnackbarSampleActivity.this) .position(Snackbar.SnackbarPosition.PARENT_CENTER) .margin(25) .text("Center Single-line snackbar")); } });
最终显示效果如下:
时间: 2024-10-06 14:49:44