當AppBarLayout 展開的時候
menu icon需要變色
找到了這個
http://stackoverflow.com/questions/30936373/collapsingtoolbarlayout-change-home-button-color-when-expanded
@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.sample_actions, menu); for(int i = 0; i < menu.size(); i++){ Drawable drawable = menu.getItem(i).getIcon(); if(drawable != null) { drawable.mutate(); drawable.setColorFilter(getResources().getColor(R.color.accent) , PorterDuff.Mode.SRC_ATOP); } } return true; }
發現可以直接改變drawable的顏色
不過home跟overflow沒有吃到效果
所以必須還要加上code
private void changeToolbarIcon(int color) { Drawable drawable = toolBar.getNavigationIcon(); if (drawable != null) { drawable.mutate(); drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } Drawable overflowIcon = toolBar.getOverflowIcon(); if (overflowIcon != null) { overflowIcon.mutate(); overflowIcon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); } }
之後在appbar監聽addOnOffsetChangedListener來變色
大致上就可以完成了 參照下面的方法來使用還可以做出漸變色的效果
http://stackoverflow.com/questions/4414673/android-color-between-two-colors-based-on-percentage
private float interpolate(float a, float b, float proportion) { return (a + ((b - a) * proportion)); } /** Returns an interpoloated color, between <code>a</code> and <code>b</code> */ private int interpolateColor(int a, int b, float proportion) { float[] hsva = new float[3]; float[] hsvb = new float[3]; Color.colorToHSV(a, hsva); Color.colorToHSV(b, hsvb); for (int i = 0; i < 3; i++) { hsvb[i] = interpolate(hsva[i], hsvb[i], proportion); } return Color.HSVToColor(hsvb); }