morristech
6/8/2019 - 11:30 AM

使用 dataBinding 来优化 fitsSystemWindows 系统边距分发

使用 dataBinding 来优化 fitsSystemWindows 系统边距分发


public class MainActivity extends BaseActivity {

    private ActivityMainBinding mBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mBinding.setInsets(new WindowInsetsBindingAdapter.WindowInset());
    }

}

/**
 * 为了给 layout_marginBottom 等提供绑定
 * @see 
 *<a href=https://github.com/oasisfeng/deagle/blob/master/library/src/main/java/com/oasisfeng/android/databinding/adapters/ViewBindingAdapter.java><a/>
 */

import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.BindingAdapter;
import android.support.v4.view.ViewCompat;
import android.view.ViewGroup;

/**
 * @author heruoxin
 * @since 2017/3/30
 */

public class WindowInsetsBindingAdapter {

    @BindingAdapter("windowInsetsRoot")
    public static void bindRootView(final ViewGroup viewGroup, final WindowInset pInset) {
        assert pInset != null;
        ViewCompat.setOnApplyWindowInsetsListener(viewGroup, (v, insets) -> {
            pInset.top = insets.getSystemWindowInsetTop();
            pInset.left = insets.getSystemWindowInsetLeft();
            pInset.bottom = insets.getSystemWindowInsetBottom();
            pInset.right = insets.getSystemWindowInsetRight();
            pInset.notifyChange();
            return insets;
        });
    }

    public static class WindowInset extends BaseObservable {

        @Bindable
        public float top;

        @Bindable
        public float left;

        @Bindable
        public float bottom;

        @Bindable
        public float right;

    }

}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:bind="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="insets"
            type="com.xxx.yyy.WindowInset" />

    </data>

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/root_container"
        android:fitsSystemWindows="true"
        bind:windowInsetsRoot="@{insets}"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <FrameLayout
            android:id="@+id/child_view"
            android:layout_marginTop="@{insets.top}"
            android:layout_marginBottom="@{insets.bottom + @dimen/some_other_margin}"
            android:background="@color/blue_A100"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </android.support.design.widget.CoordinatorLayout>