Android自定義軟鍵盤樣式:字母苹威、數字、標點三種切換

先看效果圖:


20180110144638500.png
20180110144711177.png
20180110154007315.png

1.在需要的調用軟鍵盤的activity_mian.xml中加入鍵盤控件


<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">

<android.inputmethodservice.KeyboardView
    android:id="@+id/keyboard_view"
    android:shadowRadius="0.0"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:keyPreviewLayout="@layout/key_preview_layout"
    android:background="#D6D9DE"
    android:keyBackground="@drawable/btn_keyboard_key"
    android:keyTextColor="#747474"
    android:keyTextSize="36dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:paddingLeft="95dp"
    android:paddingRight="95dp"
    android:visibility="gone"
    />

</RelativeLayout>
1.1

android:keyPreviewLayout="@layout/key_preview_layout"這個是長按鍵盤時彈出框的樣式惜犀,如果不寫,系統(tǒng)默認狠裹,默認的有時會會看不清
key_preview_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:textColor="@android:color/white"
android:gravity="center"
android:background="#80929299"/>
1.2
android:keyBackground="@drawable/btn_keyboard_key"按鍵的形狀

btn_keyboard_key.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFFFFFFF"/>
<corners android:topLeftRadius="8dip"
android:topRightRadius="8dip"
android:bottomRightRadius="8dip"
android:bottomLeftRadius="8dip" />
</shape>

2.然后在res文件夾下新建文件夾虽界,里面新建三個文件,即每種鍵盤樣式的布局分別為qwerty.xml, symbols.xml, punctuate.xml

字母鍵盤-qwerty.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Keyboard android:keyWidth="100dp" android:keyHeight="60dp"
android:horizontalGap="10dp" android:verticalGap="15dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<Row>
<Key android:codes="113" android:keyEdgeFlags="left"
android:keyLabel="q" />
<Key android:codes="119" android:keyLabel="w" />
<Key android:codes="101" android:keyLabel="e" />
<Key android:codes="114" android:keyLabel="r" />
<Key android:codes="116" android:keyLabel="t" />
<Key android:codes="121" android:keyLabel="y" />
<Key android:codes="117" android:keyLabel="u" />
<Key android:codes="105" android:keyLabel="i" />
<Key android:codes="111" android:keyLabel="o" />
<Key android:codes="112" android:keyEdgeFlags="right"
android:keyLabel="p" />
</Row>
<Row>
<Key android:horizontalGap="4.999995%p" android:codes="97"
android:keyEdgeFlags="left" android:keyLabel="a" />
<Key android:codes="115" android:keyLabel="s" />
<Key android:codes="100" android:keyLabel="d" />
<Key android:codes="102" android:keyLabel="f" />
<Key android:codes="103" android:keyLabel="g" />
<Key android:codes="104" android:keyLabel="h" />
<Key android:codes="106" android:keyLabel="j" />
<Key android:codes="107" android:keyLabel="k" />
<Key android:codes="108" android:keyEdgeFlags="right"
android:keyLabel="l" />
</Row>
<Row>
<Key android:keyWidth="110dp" android:codes="-1"
android:keyEdgeFlags="left" android:isModifier="true"
android:horizontalGap="33dp"
android:isSticky="true" android:keyIcon="@drawable/shift" />
<Key android:codes="122" android:keyLabel="z" android:horizontalGap="30dp"/>
<Key android:codes="120" android:keyLabel="x" />
<Key android:codes="99" android:keyLabel="c" />
<Key android:codes="118" android:keyLabel="v" />
<Key android:codes="98" android:keyLabel="b" />
<Key android:codes="110" android:keyLabel="n" />
<Key android:codes="109" android:keyLabel="m" />
<Key android:keyWidth="110dp" android:codes="-5"
android:horizontalGap="30dp"
android:keyEdgeFlags="right" android:isRepeatable="true"
android:keyIcon="@drawable/delete" />
</Row>
<Row android:rowEdgeFlags="bottom">
<Key android:keyWidth="110dp" android:codes="-2" android:horizontalGap="43dp"
android:keyIcon="@drawable/number" />
<Key android:keyWidth="110dp" android:codes="46"
android:keyIcon="@drawable/point" />
<Key android:keyWidth="540dp" android:codes="32"
android:isRepeatable="true" android:keyIcon="@drawable/space" />
<Key android:keyWidth="110dp" android:codes="47"
android:keyIcon="@drawable/gang"/>
<Key android:keyWidth="110dp" android:codes="-3"
android:keyEdgeFlags="right" android:keyIcon="@drawable/complete" />
</Row>
</Keyboard>
數字鍵盤-symbols.xml:

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="100dp" android:horizontalGap="10dp"
android:verticalGap="15dp" android:keyHeight="60dp">

<Row>
<Key android:codes="49" android:keyEdgeFlags="left"
android:keyLabel="1" />
<Key android:codes="50" android:keyLabel="2" />
<Key android:codes="51" android:keyLabel="3" />
<Key android:codes="52" android:keyLabel="4" />
<Key android:codes="53" android:keyLabel="5" />
<Key android:codes="54" android:keyLabel="6" />
<Key android:codes="55" android:keyLabel="7" />
<Key android:codes="55" android:keyLabel="8" />
<Key android:codes="56" android:keyLabel="9" />
<Key android:codes="48" android:keyEdgeFlags="right"
android:keyLabel="0" />
</Row>
<Row>
<Key android:codes="45" android:keyEdgeFlags="left"
android:keyLabel="-" />
<Key android:codes="47" android:keyLabel="/" />
<Key android:codes="65306" android:keyLabel=":" />
<Key android:codes="65307" android:keyLabel="涛菠;" />
<Key android:codes="65288" android:keyLabel="(" />
<Key android:codes="65289" android:keyLabel=")" />
<Key android:codes="37" android:keyLabel="%" />
<Key android:codes="64" android:keyLabel="@" />
<Key android:codes="8220" android:keyLabel="“" />
<Key android:codes="8221" android:keyEdgeFlags="right"
android:keyLabel="”" />
</Row>
<Row>
<Key android:keyWidth="110dp" android:codes="-7"
android:keyEdgeFlags="left" android:isModifier="true" android:horizontalGap="90dp"
android:isSticky="true" android:keyIcon="@drawable/punctuate" />
<Key android:codes="12290" android:keyLabel="莉御。" android:horizontalGap="30dp"/>
<Key android:codes="65292" android:keyLabel="," />
<Key android:codes="12289" android:keyLabel="碗暗、" />
<Key android:codes="65311" android:keyLabel="颈将?" />
<Key android:codes="65281" android:keyLabel="!" />
<Key android:codes="46" android:keyLabel="." />
<Key android:keyWidth="110dp" android:codes="-5"
android:horizontalGap="30dp"
android:keyEdgeFlags="right" android:isRepeatable="true"
android:keyIcon="@drawable/delete" />
</Row>
<Row android:rowEdgeFlags="bottom">
<Key android:keyWidth="110dp" android:codes="-2" android:horizontalGap="90dp"
android:keyIcon="@drawable/pinyin" />
<Key android:keyWidth="650dp" android:codes="32" android:horizontalGap="30dp"
android:isRepeatable="true" android:keyIcon="@drawable/space" />
<Key android:keyWidth="110dp" android:codes="-3" android:horizontalGap="30dp"
android:keyEdgeFlags="right" android:keyIcon="@drawable/complete" />
</Row>

</Keyboard>
標點鍵盤-punctuate.xml

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="100dp" android:horizontalGap="17dp"
android:verticalGap="15dp" android:keyHeight="60dp">

<Row>
    <Key android:codes="12304" android:keyEdgeFlags="left"
         android:keyLabel="【"  android:horizontalGap="50dp"/>
    <Key android:codes="12305" android:keyLabel="】" />
    <Key android:codes="65371" android:keyLabel="{" />
    <Key android:codes="65373" android:keyLabel="}" />
    <Key android:codes="35" android:keyLabel="#" />
    <Key android:codes="94" android:keyLabel="^" />
    <Key android:codes="42" android:keyLabel="*" />
    <Key android:codes="43" android:keyLabel="+" />
    <Key android:codes="61" android:keyEdgeFlags="right"
        android:keyLabel="=" />
</Row>
<Row>
    <Key android:codes="45" android:keyEdgeFlags="left"
        android:keyLabel="-"  android:horizontalGap="50dp"/>
    <Key android:codes="8212" android:keyLabel="—" />
    <Key android:codes="92" android:keyLabel="&#92;&#92;" />
    <Key android:codes="124" android:keyLabel="|" />
    <Key android:codes="126" android:keyLabel="~" />
    <Key android:codes="12298" android:keyLabel="《" />
    <Key android:codes="12299" android:keyLabel="》" />
    <Key android:codes="38" android:keyLabel="&#038;"/>
    <Key android:codes="65509" android:keyEdgeFlags="right"
        android:keyLabel="¥" />
</Row>
<Row>
    <Key android:keyWidth="110dp" android:codes="-7"
        android:keyEdgeFlags="left" android:isModifier="true"
        android:horizontalGap="80dp"
        android:isSticky="true" android:keyIcon="@drawable/number" />
    <Key android:codes="8230" android:keyLabel="…" android:horizontalGap="30dp"/>
    <Key android:codes="65509" android:keyLabel="¥" />
    <Key android:codes="12289" android:keyLabel="言疗、" />
    <Key android:codes="65311" android:keyLabel="晴圾?" />
    <Key android:codes="8216" android:keyLabel="‘" />
    <Key android:codes="8217" android:keyLabel="’" />
    <Key android:keyWidth="110dp" android:codes="-5"
        android:horizontalGap="30dp"
        android:keyEdgeFlags="right" android:isRepeatable="true"
        android:keyIcon="@drawable/delete" />
</Row>
<Row android:rowEdgeFlags="bottom">
    <Key android:keyWidth="110dp" android:codes="-2" android:horizontalGap="80dp"
        android:keyIcon="@drawable/pinyin" />
    <Key android:keyWidth="685dp" android:codes="32" android:horizontalGap="30dp"
        android:isRepeatable="true" android:keyIcon="@drawable/space" />
    <Key android:keyWidth="110dp" android:codes="-3" android:horizontalGap="30dp"
        android:keyEdgeFlags="right" android:keyIcon="@drawable/complete" />
</Row>

</Keyboard>
android:keyIcon="@drawable/space" 的部分沒有圖片的話可以換成 android:keyLabel=" "括號里用相應字母或符號代替

3.然后就是KeyBoardUtil工具類,網上有很多內容大同小異噪奄,我為了實現三種鍵盤的切換進行了一些改動

KeyBoardUtil.java

package com.dcdz.app.base;

import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.Keyboard.Key;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;

import com.dcdz.app.R;

import java.util.List;

public class KeyboardUtil {
private Context ctx;
private Activity act;
private KeyboardView keyboardView;
private Keyboard k1;// 字母鍵盤
private Keyboard k2;// 數字鍵盤
private Keyboard k3;//標點符號鍵盤
public boolean isnun = false;// 是否數據鍵盤
public boolean ispun = false;//是否標點鍵盤
public boolean isupper = false;// 是否大寫

public static final int KEYCODE_PUN = -7;

private EditText ed;

public KeyboardUtil(Activity act, Context ctx, EditText edit) {
    this.act = act;
    this.ctx = ctx;
    this.ed = edit;
    k1 = new Keyboard(ctx, R.xml.qwerty);
    k2 = new Keyboard(ctx, R.xml.symbols);
    k3 = new Keyboard(ctx,R.xml.punctuate);
    keyboardView = (KeyboardView) act.findViewById(R.id.keyboard_view);
    keyboardView.setKeyboard(k1);
    keyboardView.setEnabled(true);
    keyboardView.setPreviewEnabled(true);
    keyboardView.setOnKeyboardActionListener(listener);

}

private OnKeyboardActionListener listener = new OnKeyboardActionListener() {
    @Override
    public void swipeUp() {
    }

    @Override
    public void swipeRight() {
    }

    @Override
    public void swipeLeft() {
    }

    @Override
    public void swipeDown() {
    }

    @Override
    public void onText(CharSequence text) {
    }

    @Override
    public void onRelease(int primaryCode) {
    }

    @Override
    public void onPress(int primaryCode) {
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) {
        Editable editable = ed.getText();
        int start = ed.getSelectionStart();
        if (primaryCode == Keyboard.KEYCODE_CANCEL) {// 完成
            hideKeyboard();
        } else if (primaryCode == Keyboard.KEYCODE_DELETE) {// 回退
            if (editable != null && editable.length() > 0) {
                if (start > 0) {
                    editable.delete(start - 1, start);
                }
            }
        } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {// 大小寫切換
            changeKey();
            keyboardView.setKeyboard(k1);


        } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {// 數字鍵盤切換
            if (isnun) {
                isnun = false;
                keyboardView.setKeyboard(k1);
            } else {
                isnun = true;
                keyboardView.setKeyboard(k2);
            }
        }else if(primaryCode == KEYCODE_PUN){
            if(ispun){
                ispun = false;
                keyboardView.setKeyboard(k2);
            }else {
                ispun = true;
                keyboardView.setKeyboard(k3);
            }
        }
        else if (primaryCode == 57419) { // go left
            if (start > 0) {
                ed.setSelection(start - 1);
            }
        } else if (primaryCode == 57421) { // go right
            if (start < ed.length()) {
                ed.setSelection(start + 1);
            }
        } else {
            editable.insert(start, Character.toString((char) primaryCode));
        }
    }
};
/**
 * 鍵盤大小寫切換
 */
private void changeKey() {
    List<Key> keylist = k1.getKeys();
    if (isupper) {//大寫切換小寫
        isupper = false;
        for(Key key:keylist){
            if (key.label!=null && isword(key.label.toString())) {
                key.label = key.label.toString().toLowerCase();
                key.codes[0] = key.codes[0]+32;
            }
        }
    } else {//小寫切換大寫
        isupper = true;
        for(Key key:keylist){
            if (key.label!=null && isword(key.label.toString())) {
                key.label = key.label.toString().toUpperCase();
                key.codes[0] = key.codes[0]-32;
            }
        }
    }
}

public void showKeyboard() {
    int visibility = keyboardView.getVisibility();
    if (visibility == View.GONE || visibility == View.INVISIBLE) {
        keyboardView.setVisibility(View.VISIBLE);
    }
}

public void hideKeyboard() {
    int visibility = keyboardView.getVisibility();
    if (visibility == View.VISIBLE) {
        keyboardView.setVisibility(View.INVISIBLE);
    }
}

private boolean isword(String str){
    String wordstr = "abcdefghijklmnopqrstuvwxyz";
    if (wordstr.indexOf(str.toLowerCase())>-1) {
        return true;
    }
    return false;
}

}

4.最后是調用

4.1在Fragment里調

一般的項目都是在Fragment里調的死姚,這個根據你的文本框的位置具體來定吧

我這邊內容較多,只寫關鍵代碼

public class UserLoginFragment extends SupportFragment {
FragmentFingerUserloginBinding binding;
private EditText etUserName;
private EditText etPassword;

private Context ctx;
private Activity act;
private KeyboardView keyboardView;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_finger_userlogin, container, false);

    act = getActivity();
    ctx = getActivity().getBaseContext();
    keyboardView = (KeyboardView) getActivity().findViewById(R.id.keyboard_view);
   
    etUserName = binding.etUsername;
    etPassword = binding.etPassword;

    initView();
    return binding.getRoot();
}

private void initView() {
    if (binding != null) {
        etUserName.requestFocus();

// etUserName.setFocusableInTouchMode(true);
etUserName.addTextChangedListener(watcher);
etPassword.addTextChangedListener(watcher);

        etUserName.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        etPassword.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

        //調用自定義鍵盤
        etUserName.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                keyboardView.setKeyboard(k1);

// int inputback = etUserName.getInputType();
// etUserName.setInputType(InputType.TYPE_NULL);
new KeyboardUtil(act,act.getBaseContext(), etUserName).showKeyboard();
// etUserName.setInputType(inputback);
return false;
}
});
etPassword.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
keyboardView.setKeyboard(k2);
new KeyboardUtil(act, act.getBaseContext(), etPassword).showKeyboard();
return false;
}
});
}

}

}

4.2在Activity里調勤篮,在Activity里調我是為了在這里實現觸摸屏幕其他位置隱藏軟鍵盤

關鍵代碼

public class FingerActivity extends SupportActivity {
private KeyboardView keyboardView;

@SuppressLint("ResourceType")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_finger);

    keyboardView = (KeyboardView) findViewById(R.id.keyboard_view);

    initView();
    loadRootFragment(new UserLoginFragment());
}

public boolean onTouchEvent(MotionEvent event) {
if(null != this.getCurrentFocus()){
/**
* 點擊空白位置 隱藏軟鍵盤
*/
keyboardView.setVisibility(View.INVISIBLE);
}
return super .onTouchEvent(event);
}
5到這里即基本可以實現了都毒,在使用的時候肯定還會遇到很多小問題,這里也不一 一列舉了碰缔。

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末账劲,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子金抡,更是在濱河造成了極大的恐慌瀑焦,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件梗肝,死亡現場離奇詭異榛瓮,居然都是意外死亡,警方通過查閱死者的電腦和手機巫击,發(fā)現死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門禀晓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人坝锰,你說我怎么就攤上這事粹懒。” “怎么了顷级?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵崎淳,是天一觀的道長。 經常有香客問我愕把,道長拣凹,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任恨豁,我火速辦了婚禮嚣镜,結果婚禮上,老公的妹妹穿的比我還像新娘橘蜜。我一直安慰自己菊匿,他們只是感情好,可當我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布计福。 她就那樣靜靜地躺著跌捆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪象颖。 梳的紋絲不亂的頭發(fā)上佩厚,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天,我揣著相機與錄音说订,去河邊找鬼抄瓦。 笑死,一個胖子當著我的面吹牛陶冷,可吹牛的內容都是我干的钙姊。 我是一名探鬼主播,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼埂伦,長吁一口氣:“原來是場噩夢啊……” “哼煞额!你這毒婦竟也來了?” 一聲冷哼從身側響起沾谜,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤膊毁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后类早,有當地人在樹林里發(fā)現了一具尸體媚媒,經...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年涩僻,在試婚紗的時候發(fā)現自己被綠了缭召。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡逆日,死狀恐怖嵌巷,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情室抽,我是刑警寧澤搪哪,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站坪圾,受9級特大地震影響晓折,放射性物質發(fā)生泄漏惑朦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一漓概、第九天 我趴在偏房一處隱蔽的房頂上張望漾月。 院中可真熱鬧,春花似錦胃珍、人聲如沸梁肿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽吩蔑。三九已至,卻和暖如春填抬,著一層夾襖步出監(jiān)牢的瞬間烛芬,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工痴奏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蛀骇,地道東北人。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓读拆,卻偏偏與公主長得像擅憔,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子檐晕,可洞房花燭夜當晚...
    茶點故事閱讀 45,033評論 2 355