我目前正在嘗試使用CoordinatorLayout
類來調整Toolbar
不透明度,具體取決於滾動位置的ScrollView
。我成功地做了這個「手動鏈接」這兩個視圖,聆聽滾動事件ScrollView
並報告我的背景的Alpha值。使用CoordinatorLayout滾動時更改工具欄背景Alpha值
的有用的行爲是:
工具欄是在透明狀態(文本和背景)開始,並最終完全白色背景和黑色文本當一個視圖被完全滾動。
該行爲大致是這樣的:Youtube video。
當前實現
佈局文件(簡化的)
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<my.package.widgets.DetailsTop
android:id="@+id/layout_details_top"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<my.package.widgets.DetailsBottom
android:id="@+id/layout_details_bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00FFFFFF"/>
</RelativeLayout>
片段執行
public class SearchVehicleDetailsFragment extends BaseFragment<SearchContract.ParentView> {
@Bind(R.id.layout_details_top) DetailsTop detailsTopLayout;
@Bind(R.id.layout_details_bottom) DetailsBottom detailsBottomLayout;
@Bind(R.id.scrollView) ScrollView scrollView;
@Bind(R.id.toolbar) Toolbar toolbar;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
float alpha = (float) scrollView.getScrollY()/vehicleDetailsTopLayout.getHeight();
toolbar.setBackgroundColor(getColorWithAlpha(alpha, getResources().getColor(R.color.white)));
toolbar.setTitleTextColor(getColorWithAlpha(alpha, getResources().getColor(R.color.dark_grey)));
}
});
}
public static int getColorWithAlpha(float alpha, int baseColor) {
int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24;
int rgb = 0x00ffffff & baseColor;
return a + rgb;
}
}
問題
但是,即使以前的代碼片段是一個特別簡單的解決方案,似乎完美工作,但我只是有點困惑,爲什麼它不適用於CoordinatorLayout
。另外,我發現一個人似乎已經通過自定義的CoordinatorLayout.Behavior<android.support.v7.widget.Toolbar>
實現來完成這項任務。你可以看看他的custom CoordinatorLayout.Behavior implementation。他還提供了一些關於Medium的細節。然而,由於很多剛<android.support.v7.widget.Toolbar .../>
,而不是完整Toolbar
標籤和強大的缺乏支持設計庫的作品如何這部分的理解,我從來沒有能夠實現它...
問題
我想了解CoordinatorLayout
及其周圍的所有類如何協同工作。所以我可能會實現我正在尋找的行爲,即:將ScrollView滾動位置鏈接到工具欄背景顏色的Alpha值。
顯然,如果你還知道如何實現這一切,我將非常高興地看到你片斷:)
它看起來像一個很酷的概念很好的一個兄弟 –
如果你正在尋找coordinatorlayouts的詳細解釋,請檢查一下。 https://medium.com/google-developers/intercepting-everything-with-coordinatorlayout-behaviors-8c6adc140c26#.nvsysrem6 –