KeyBoardObservable.java 2.29 KB
package com.people.speech.view;

import android.content.Context;
import android.view.View;

import androidx.annotation.NonNull;


import com.people.speech.utils.KeyBoardObserver;
import com.people.speech.utils.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author LiuKun
 * @date 2023/5/2  17:26
 * @Description:监听器
 */
public class KeyBoardObservable {

    private int lastHeight;
    private List<KeyBoardObserver> observers;

    private boolean keyBoardVisibility;

    /**
     * 注册监听
     *
     * @param listener
     */
    public void register(@NonNull KeyBoardObserver listener) {
        if (observers == null) {
            observers = new ArrayList<>();
        }
        observers.add(listener);
    }

    /**
     * 注销
     *
     * @param listener
     */
    public void unRegister(@NonNull KeyBoardObserver listener) {
        if (observers != null) {
            observers.remove(listener);
        }
    }

    /**
     * 抢先测量
     *
     * @param heightMeasureSpec
     */
    public void beforeMeasure(Context context, int heightMeasureSpec) {
        int height = View.MeasureSpec.getSize(heightMeasureSpec);
        if (lastHeight == 0) {
            lastHeight = height;
            return;
        }
        if (lastHeight == height) {
            //没有发生挤压
            return;
        }
        final int offset = lastHeight - height;
        /*if (Math.abs(offset) < DensityUtil.dp2px(80)) {
            //80 dp 挤压阈值
            return;
        }*/

        if (offset > 0) {
            keyBoardVisibility = true;
        } else {
            keyBoardVisibility = false;
        }
        int keyBoardHeight = Math.abs(offset);
        SharedPreferencesUtils.saveKeyBoardHeight(context, keyBoardHeight);
        update(keyBoardVisibility, keyBoardHeight);
        lastHeight = height;
    }

    public boolean isKeyBoardVisibility() {
        return keyBoardVisibility;
    }

    /**
     * 通知更新
     *
     * @param keyBoardVisibility
     */
    private void update(final boolean keyBoardVisibility, int keyBoardHeight) {
        if (observers != null) {
            for (KeyBoardObserver observable : observers) {
                observable.update(keyBoardVisibility, keyBoardHeight);
            }
        }
    }
}