1. 程式人生 > >Android軟鍵盤與EditText近乎完美的互動

Android軟鍵盤與EditText近乎完美的互動

fastandrutlis開發框架
fastandrutlis開發框架

android使用EditText的時候總是遇到一些很不爽的問題:

無圖無真相。。
1.點選螢幕其他的任何位置,軟鍵盤不會隱藏
2.軟鍵盤會把輸入框遮蓋掉


bb.gif
bb.gif

3.軟鍵盤會把介面頂起


cc.gif
cc.gif
由於對鍵盤和EditText的種種不爽,就弄了一個以下東西
aa.gif
aa.gif

一.首先要知道怎麼用程式碼控制軟鍵盤的顯示隱藏

以下是軟鍵盤顯示隱藏類 KeyBoardUtils.java


import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * @author laijian
 * @version 2017/8/29
 * @Copyright (C)下午2:55 , Suntektech
 */
public class KeyBoardUtils {
    /**
     * 開啟軟鍵盤
     *
     * @param mEditText
     * @param mContext
     */
    public static void openKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 關閉軟鍵盤
     *
     * @param mEditText
     * @param mContext
     */
    public static void closeKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }


    /**
     * des:隱藏軟鍵盤,這種方式引數為activity
     *
     * @param activity
     */
    public static void hideInputForce(Activity activity) {
        if (activity == null || activity.getCurrentFocus() == null)
            return;
        ((InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 開啟鍵盤
     **/
    public static void showInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }




}

這個類沒什麼好說的

二.要知道軟鍵盤彈出時的高度

獲取軟鍵盤彈出的高度是為了建立一個自適應的dialog,鍵盤彈出時就會在鍵盤上方顯示一個帶EditText的dialog
以下是獲取軟鍵盤高度的類 KeyBoardHeightUtils.java


import android.app.Activity;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

/**
 * @author laijian
 * @version 2017/8/31
 * @Copyright (C)上午11:11 , Suntektech
 */
public class KeyBoardHeightUtils {
    private View mChildOfContent;//activity 的佈局View
    private int usableHeightPrevious;//activity的View的可視高度
    private KeyBoardHigthListener keyBoardHigthListener;

    public static KeyBoardHeightUtils setKeyBoardHeigthListener(Activity activity, KeyBoardHigthListener keyBoardHigthListener) {
        return new KeyBoardHeightUtils(activity, keyBoardHigthListener);
    }

    public void removeKeyboardHeightListener() {
        if (mChildOfContent == null) {
            return;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(globalLayoutListener);
        } else {
            mChildOfContent.getViewTreeObserver().removeOnGlobalLayoutListener(globalLayoutListener);
        }
    }

    private KeyBoardHeightUtils(final Activity activity, KeyBoardHigthListener keyBoardHigthListener) {
        this.keyBoardHigthListener = keyBoardHigthListener;
//獲取安卓activity的最頂級控制元件
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);//
        mChildOfContent = content.getChildAt(0);
 //監聽檢視高度變化      mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
//點選父控制元件隱藏軟鍵盤
        mChildOfContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtils.hideInputForce(activity);
            }
        });
    }

    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            possiblyResizeChildOfContent();
        }
    };


    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
//為了去除無謂的干擾,限制下高度
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                keyBoardHigthListener.keyBoardHigthListener(usableHeightSansKeyboard - heightDifference, true, mChildOfContent);
            } else {
                keyBoardHigthListener.keyBoardHigthListener(usableHeightSansKeyboard, false, mChildOfContent);
            }
            usableHeightPrevious = usableHeightNow;
        }
    }
//獲取控制元件在螢幕的可視高度,就是介面除去了標題欄、除去了被軟鍵盤擋住的部分,所剩下的矩形區域
    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }


    interface KeyBoardHigthListener {//這個回撥類寫的不好,請自行修改
        void keyBoardHigthListener(int heigth, boolean showKeyBoard, View contentView);
    }


}

這程式碼也不多 也不難理解

三.要知道EditText控制元件是否被遮蓋

判斷EditText控制元件是否被遮蓋是為了彈出一個帶EditText 的 dialog 這樣就不會說EditText被覆蓋後 不知道輸入了些什麼內容

以下是檢測EditText控制元件是否被覆蓋

 private boolean checkViewVisiable() {
        Rect localRect = new Rect();
        boolean visiable = edtextVew.getLocalVisibleRect(localRect);
        System.out.println("visiable=" + visiable);
        return visiable;
    }

以下是判斷獲取的焦點是不是EditText

  View childView = contentView.findFocus();
                if (childView != null) {
                    if (childView instanceof EditText) {
                        edtextVew = (EditText) childView;

以下類就是關鍵類,判斷EditText是否被覆蓋,彈dialog等
KeyBoardUI.java


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.univercityapp.convergelibrary.widget.NullMenuEditText;

/**
 * @author laijian
 * @version 2017/8/31
 * @Copyright (C)上午11:57 , Suntektech
 */
public class KeyBoardUI implements KeyBoardHeightUtils.KeyBoardHigthListener {

    private EditText edtextVew;//activity的輸入框
    private Activity activity;
    private Dialog mDialog;
    private NullMenuEditText popuEdtext;//popu的輸入框
    private int screenWeight = 0;//螢幕寬度
    private KeyBoardHeightUtils keyBoardHeightUtils;

    public static KeyBoardUI buildKeyBoardUI(Activity activity) {
        return new KeyBoardUI(activity);
    }


    private KeyBoardUI(Activity activity) {
        this.activity = activity;
        getScreen();
        initDialog();
        keyBoardHeightUtils = KeyBoardHeightUtils.setKeyBoardHeigthListener(activity, this);
    }

    private void getScreen() {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWeight = dm.widthPixels;
    }

    private void initDialog() {
        LayoutInflater inflater = (LayoutInflater) activity.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popuView = inflater.inflate(ResourcesUtils.getLayoutResources(activity, "popuwindow"), null);
        RelativeLayout populay = (RelativeLayout) popuView.findViewById(ResourcesUtils.getIdResources(activity, "popu_lay"));
        popuEdtext = (NullMenuEditText) popuView.findViewById(ResourcesUtils.getIdResources(activity, "ed_text"));
        mDialog = new Dialog(activity, ResourcesUtils.getStyleResources(activity, "dialog"));
        mDialog.setContentView(popuView);
        populay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtils.closeKeybord(popuEdtext, activity);
                mDialog.dismiss();
            }
        });

    }

    @Override
    public void keyBoardHigthListener(int heigth, boolean showKeyBoard, View contentView) {
        if (showKeyBoard) {
            if (contentView != null) {
                View childView = contentView.findFocus();
                if (childView != null) {
                    if (childView instanceof EditText) {
                        edtextVew = (EditText) childView;
                        if (!checkViewVisiable()) {
                            mDialog.show();
//重新調整dialog的高度
                            Window dialogWindow = mDialog.getWindow();
                            WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 獲取對話方塊當前的引數值
                            p.height = heigth; 
                            p.width = screenWeight; 
                            dialogWindow.setAttributes(p);
                            dialogWindow.setWindowAnimations(ResourcesUtils.getStyleResources(activity, "PopupAnimation"));
                            onEdChange();
                            KeyBoardUtils.openKeybord(edtextVew, activity);
                        } else {
                            if (mDialog != null) {
                                mDialog.dismiss();
                            }
                        }
                    }
                }
            }
        } else {
            if (mDialog != null) {
                mDialog.dismiss();
            }
        }
    }

    private boolean checkViewVisiable() {
        Rect localRect = new Rect();
        boolean visiable = edtextVew.getLocalVisibleRect(localRect);
        System.out.println("visiable=" + visiable);
        return visiable;
    }

    private void onEdChange() {
        String hintStr = "";
        String text = "";
        if (!TextUtils.isEmpty(edtextVew.getText())) {
            text = edtextVew.getText().toString();
        }
        if (!TextUtils.isEmpty(edtextVew.getHint())) {
            hintStr = edtextVew.getHint().toString();
        }
        popuEdtext.findFocus();
        popuEdtext.setInputType(edtextVew.getInputType());
        popuEdtext.setHint(hintStr);
        popuEdtext.setText(text);
        popuEdtext.setSelection(text.length());
        popuEdtext.setMaxEms(edtextVew.getMaxEms());
        popuEdtext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                edtextVew.setText(s);
                edtextVew.setSelection(s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        popuEdtext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == 0) {
                    KeyBoardUtils.closeKeybord(popuEdtext, activity);
                    mDialog.dismiss();
                    return true;
                }
                return false;
            }
        });
    }

    public void removeKeyboardHeightListener() {
        keyBoardHeightUtils.removeKeyboardHeightListener();
    }
}

四.禁止EditText長按出複製貼上

NullMenuEditText.java


/**
 * @author laijian
 * @version 2017/8/30
 * @Copyright (C)下午5:26 , Suntektech
 */

import android.content.Context;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

/**
 * Created by jianjun.lin on 16/4/12.
 */
public class NullMenuEditText extends EditText {

    boolean canPaste() {
        return false;
    }

    boolean canCut() {
        return false;
    }

    boolean canCopy() {
        return false;
    }

    boolean canSelectAllText() {
        return false;
    }

    boolean canSelectText() {
        return false;
    }

    boolean textCanBeSelected() {
        return false;
    }

    public NullMenuEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setLongClickable(false);
        setTextIsSelectable(false);
        setCustomSelectionActionModeCallback(new ActionMode.Callback() {
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                return false;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        });

    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        return true;
    }
}

五.相關xml資源

還有一些動畫效果資源
popup_enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="100"
        android:fromYDelta="1"
        android:toYDelta="0" />
    <alpha
        android:duration="100"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>

popup_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="100"
        android:fromYDelta="0"
        android:toYDelta="1" />
    <alpha
        android:duration="100"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />
</set>

styles資源

 <style name="PopupAnimation" mce_bogus="1" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/popup_enter</item>
        <item name="android:windowExitAnimation">@anim/popup_exit</item>
    </style>

    <style name="dialog" parent="android:style/Theme.Dialog">
        <item name="android:background">#00000000</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

layout檔案
popuwindow.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popu_lay"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#00000000">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#ffffff"
        android:orientation="vertical"
        android:paddingTop="2dp">

        <com.univercityapp.convergelibrary.widget.NullMenuEditText
            android:id="@+id/ed_text"
            android:layout_width="match_parent"
            android:layout_height="36dp"
            android:paddingLeft="6dp"
            android:background="#ffffff"
            android:gravity="center_vertical"
            android:inputType="text"
            android:maxLines="1"
            android:scrollHorizontally="true"
            android:textSize="16sp" />
    </LinearLayout>
</RelativeLayout>

六.獲取R的資源utils

ResourcesUtils.java


import android.content.Context;
import android.content.res.Resources;

import java.lang.reflect.Field;

/**
 * Created by laijian code on 2016-10-19.
 */
public class ResourcesUtils {
    public static int getIdResources(Context context, String idName) {
        Resources res = context.getResources();
        return res.getIdentifier(idName, "id", context.getPackageName());
    }
    public static int getDrawableResources(Context context, String drawableName) {
        Resources res = context.getResources();
        return res.getIdentifier(drawableName, "drawable", context.getPackageName());
    }

    public static int getColorResources(Context context, String colorName) {
        Resources res = context.getResources();
        return res.getIdentifier(colorName, "color", context.getPackageName());
    }

    public static int getStringResources(Context context, String stringName) {
        Resources res = context.getResources();
        return res.getIdentifier(stringName, "string", context.getPackageName());
    }

    public static int getLayoutResources(Context context, String LayoutName) {
        Resources res = context.getResources();
        return res.getIdentifier(LayoutName, "layout", context.getPackageName());
    }

    public static int getAttrResources(Context context, String attrName) {
        Resources res = context.getResources();
        return res.getIdentifier(attrName, "attr", context.getPackageName());
    }

    public static int getStyleResources(Context context, String attrName) {
        Resources res = context.getResources();
        return res.getIdentifier(attrName, "style", context.getPackageName());
    }

    /**
     * context.getResources().getIdentifier 無法獲取到 styleable 的資料
     *
     * @param name
     * @return
     * @paramcontext
     */

    public static int getStyleable(Context context, String name) {

        return ((Integer) getResourceId(context, name, "styleable")).intValue();

    }

    /**
     * 獲取 styleable 的 ID 號陣列
     *
     * @param name
     * @return
     * @paramcontext
     */
    public static int[] getStyleableArray(Context context, String name) {

        return (int[]) getResourceId(context, name, "styleable");

    }
    /**
     * 對於 context.getResources().getIdentifier 無法獲取的資料 , 或者陣列
     * <p/>
     * 資源反射值
     *
     * @param name
     * @param type
     * @return
     * @paramcontext
     */

    private static Object getResourceId(Context context, String name, String type) {

        String className = context.getPackageName() + ".R";

        try {

            Class<?> cls = Class.forName(className);

            for (Class<?> childClass : cls.getClasses()) {

                String simple = childClass.getSimpleName();

                if (simple.equals(type)) {

                    for (Field field : childClass.getFields()) {

                        String fieldName = field.getName();
                        if (fieldName.equals(name)) {
                            System.out.println(fieldName);
                            return field.get(null);

                        }

                    }

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }
}

七.如何使用

使用非常簡單,在需要的activity的oncreat方法新增

        KeyBoardUI.buildKeyBoardUI(this);

在AndroidManifest.xml用到上面方法的activity新增

android:windowSoftInputMode="adjustResize"