仿QQ微信点击EditText布局随软键盘的弹出顶上去

主要原理:监听软键盘的弹出,调用ScrollView的
fullScroll(ScrollView.FOCUS_DOWN);或者是scrollTo(0, 1000)的方法

已如下xml布局为例:

总得来说就是将需要向上顶的布局写在ScrollView中。理解后可略过。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_contain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:fitsSystemWindows="true">

<include
    android:id="@+id/title"
    layout="@layout/include_login_header" />

<ScrollView
    android:id="@+id/sv_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/title">


    <RelativeLayout
        android:id="@+id/rl_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical">


        <ImageView
            android:id="@+id/iv_login_logo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="40dp"
            android:src="@mipmap/logo_login" />

        <EditText
            android:id="@+id/et_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/iv_login_logo"
            android:layout_marginLeft="38dp"
            android:layout_marginRight="38dp"
            android:layout_marginTop="58dp"
            android:background="@null"
            android:hint="@string/login_username"
            android:inputType="phone"
            android:paddingBottom="12dp"
            android:singleLine="true"
            android:textColorHint="@color/search_edittext_hint"
            android:textSize="@dimen/font_size_14" />

        <View
            android:id="@+id/v_line1"
            style="@style/horizontal_line_gray"
            android:layout_below="@+id/et_username"
            android:layout_marginLeft="38dp"
            android:layout_marginRight="38dp" />

        <EditText
            android:id="@+id/et_passwork"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/v_line1"
            android:layout_marginLeft="38dp"
            android:layout_marginRight="38dp"
            android:layout_marginTop="16dp"
            android:background="@null"
            android:hint="@string/login_password"
            android:inputType="textPassword"
            android:paddingBottom="12dp"
            android:singleLine="true"
            android:textColorHint="@color/search_edittext_hint"
            android:textSize="@dimen/font_size_14" />

        <View
            android:id="@+id/v_line2"
            style="@style/horizontal_line_gray"
            android:layout_below="@+id/et_passwork"
            android:layout_marginLeft="38dp"
            android:layout_marginRight="38dp" />

        <RelativeLayout
            android:id="@+id/rl_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/v_line2">

            <TextView
                android:id="@+id/tv_register"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="30dp"
                android:padding="8dp"
                android:text="@string/login_register"
                android:textColor="@color/search_edittext_hint" />

            <TextView
                android:id="@+id/tv_login_forget"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="30dp"
                android:padding="8dp"
                android:text="@string/login_forget"
                android:textColor="@color/search_edittext_hint" />
        </RelativeLayout>

        <Button
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:layout_alignParentBottom="true"
            android:layout_below="@+id/rl_1"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="38dp"
            android:layout_marginRight="38dp"
            android:layout_marginTop="22dp"
            android:background="@drawable/btn_normal_bg"
            android:gravity="center"
            android:text="@string/login_btn"
            android:textColor="@color/white"
            android:textSize="@dimen/font_size_15" />

    </RelativeLayout>

</ScrollView>

</RelativeLayout>
首先提供一个软键盘监听的工具类
package com.xinsundoc.doctor.utils;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ScrollView;


/**
 * 类名称:KeyboardUtil<br>
 * 内容摘要: 监听软键盘显示与隐藏
 */
public class KeyboardUtil {
    private static final String TAG = "KeyboardUtil";

    public static KeyboardUtil assistActivity(Activity activity, int viewId) {
        return new KeyboardUtil(activity, viewId);
    }

    private View mChildOfContent;
    private ScrollView mScrollView; //从activity传进来的ScrollView

    private KeyboardUtil(Activity activity, int viewId) {
        FrameLayout content = (FrameLayout) activity
                .findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mScrollView = (ScrollView) content.findViewById(viewId); //从activity       传进来的ScrollView
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    possiblyResizeChildOfContent();
                }
            });
}

    private void possiblyResizeChildOfContent() {
        int contentHeight = mChildOfContent.getRootView().getHeight();
        int curDisplayHeight = computeUsableHeight();
        if (contentHeight - curDisplayHeight > contentHeight / 4) { //软键盘弹出
            Log.e(TAG, "possiblyResizeChildOfContent: 软键盘弹出" );
//                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
    //将ScrollView滑动到底部
    //这里不开线程的话,会出现点击第二个输入框不顶上去的bug,
    //初步估计是mScrollView.scrollTo(0, 1000);的原因(最好使用handler)
           new Thread(){
                @Override
                public void run() {
                    mScrollView.scrollBy(0, 1000);
                }
            }.start();
            if(mKeyBoardOpenListener != null){
                mKeyBoardOpenListener.open();
            }
        } else {  //软键盘关闭
            if(mKeyBoardOpenListener != null){
                mKeyBoardOpenListener.close();
            }
            Log.e(TAG, "possiblyResizeChildOfContent: 软键盘关闭" );
        }
}

    /**
     * 获取屏幕可显示区域高度
     *
     * @return
     */
    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
       return r.height();
    }

    private KeyBoardOpenListener mKeyBoardOpenListener;
     /**
     * 给其他类提供软键盘弹起关闭的监听
     *
     */
    public interface KeyBoardOpenListener{
        void open();
        void close();
    }
    public void setOnKeyBoardOpenListener(KeyBoardOpenListener mKeyBoardOpenListener){
        this.mKeyBoardOpenListener = mKeyBoardOpenListener;
    }
}
方法一:使用fullScroll(ScrollView.FOCUS_DOWN):

使用者中方法有一个问题:
如果一个ScrollView中有多个EditText,不管你点击哪个EditText调起软键盘,调用fullScroll(ScrollView.FOCUS_DOWN)方法后都会将焦点给最底部的那个EditText。
解决方法:
1.通过EditText的setOnTouchListener()方法获取首次点击的是哪个EditText();
2.在软键盘的监听方法open()中调用editText.requestFocus();

public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
@BindView(R.id.et_passwork)
EditText password;
@BindView(R.id.et_username)
EditText mobile;
@BindView(R.id.tv_main_title)

private EditText mEdittext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login2);
    ButterKnife.bind(this);

    inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    KeyboardUtil keyboardUtil = KeyboardUtil.assistActivity(this, R.id.sv_content);
    keyboardUtil.setOnKeyBoardOpenListener(new KeyboardUtil.KeyBoardOpenListener() {
        @Override
        public void open() {
            if(mEdittext != null){
                mEdittext.requestFocus(); //请求获取焦点
            }
        }

        @Override
        public void close() {

        }
    });

    mobile.setOnTouchListener(new MyOnTouchListener());
    password.setOnTouchListener(new MyOnTouchListener());
}

/**
 * Edittext的监听事件
 */
class MyOnTouchListener implements View.OnTouchListener {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()){
            case R.id.et_username:
                mEdittext = mobile;
                Log.e(TAG, "onTouch: mobile点击了");
                break;
            case R.id.et_passwork:
                mEdittext = password;
                Log.e(TAG, "onTouch: password点击了");
                break;
        }
        return false;
    }
}
}
方法二:使用scrollTo(0, 100)开新线程:

在软键盘弹起方法中调用

//这里不开新线程的话,会出现点击第二个输入框不顶上去的bug,
//初步估计是mScrollView.scrollTo(0, 1000);的原因 最好使用handler开新线程
   new Thread(){
                @Override
                public void run() {
                    mScrollView.scrollBy(0, 1000);
                }
            }.start();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容