Google在2014年发布了Material Design语言,紧接着第二年发布了官方support包,可以支持在低版本上手机使用这些控件。但是这么长时间过去了,国内主流app几乎都没有遵循这种规范,原因也很好理解了,这篇文章分析的比较到位(为什么Material Design没在国产App中流行起来)。最近有机会重头开始做一个APP,这是一个很好的机会践行Material Design,这里把学习support包的一些心得记录一下,与大家共同交流学习。首先是第一个控件Snackbar:
Snackbar和Toast很相似,不过是从屏幕最下方推出来,并且里面可以带button支持用户点击。它的使用很简单:
Snackbar.make(view, "You Click the Button", Snackbar.LENGTH_LONG).show();
Snackbar.make(view, "You Click the Button", Snackbar.LENGTH_LONG) .setAction("返回", new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }) .show();
private Snackbar(ViewGroup parent) { mTargetParent = parent; mContext = parent.getContext(); ThemeUtils.checkAppCompatTheme(mContext); LayoutInflater inflater = LayoutInflater.from(mContext); mView = (SnackbarLayout) inflater.inflate( R.layout.design_layout_snackbar, mTargetParent, false); }
public static Snackbar make(@NonNull View view, @NonNull CharSequence text, @Duration int duration) { <span style="color:#ff0000;">Snackbar snackbar = new Snackbar(findSuitableParent(view));</span> snackbar.setText(text); snackbar.setDuration(duration); return snackbar; }
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; }