完美解决:软键盘弹出,根据软键盘高度,将所有布局顶上去

完美解决:软键盘弹出,根据软键盘高度,将所有布局顶上去_第1张图片

实现软键盘弹出,登陆按钮以上全部上推;下面直接贴代码

布局:里面的dimen自己设定吧,很简单




    

        

            

            

                

                
            


            

                

                
            

            

                

                

                

                

            

            

            
核心方法:
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;

/**
 *.
 * 实现弹出软键盘时 整个布局向上平移,解决遮挡问题
 * 在onCreate中添加监听,在onDestroy中remove监听
 */
public class CustomGlobalLayoutListener implements OnGlobalLayoutListener {

    private Context mContext;
    private View mRootView;
    private View mScrollToView;

    /**
     * @param context      context
     * @param rootView     可以滚动的布局
     * @param scrollToView 界面上被遮挡的位于最底部的布局(控件)
     */
    public CustomGlobalLayoutListener(Context context, View rootView, View scrollToView) {
        this.mContext = context;
        this.mRootView = rootView;
        this.mScrollToView = scrollToView;
    }

    @Override
    public void onGlobalLayout() {
        Rect rect = new Rect();
        mRootView.getWindowVisibleDisplayFrame(rect);
        int rootInvisibleHeight = mRootView.getRootView().getHeight() - rect.bottom;
        if (rootInvisibleHeight > 100) {
            int[] location = new int[2];
            mScrollToView.getLocationInWindow(location);
            int scrollHeight = (location[1] + mScrollToView.getHeight()) - rect.bottom;
            mRootView.scrollTo(0, scrollHeight + Utils.dip2px(mContext, 30));
        } else {
            mRootView.scrollTo(0, 0);
        }
    }
}
应用在Activity中:

private CustomGlobalLayoutListener customGlobalLayoutListener;


customGlobalLayoutListener = new CustomGlobalLayoutListener(this, scrollView, mBtnNextStep);
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(customGlobalLayoutListener);
        
        
        @Override
    protected void onDestroy() {//防止内存溢出
        super.onDestroy();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(customGlobalLayoutListener);
        } else {
            scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(customGlobalLayoutListener);
        }
    }

配置文件中:

android:windowSoftInputMode="stateHidden|adjustResize"
缺点:

布局会压缩


你可能感兴趣的:(AndroidUI,android)