Android 自定義數字鍵盤實現方法

自定義數字鍵盤

1.鍵盤布局
horizontalGap:按鍵間的水平間隔
keyHeight:按鍵高度以%或者%p結尾
keyWidth:按鍵寬度,”33.33333%p”
verticalGap:按鍵間的垂直間隔
codes:可以是系統給的固定值也可以是自定義的值

  <?xml version="1.0" encoding="utf-8"?>
 <Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:horizontalGap="1dp"
android:keyHeight="8%p"
android:keyWidth="33.33333%p"
android:verticalGap="1dp">
<Row>
    <Key
        android:codes="49"
        android:keyLabel="1"></Key>
    <Key
        android:codes="50"
        android:keyLabel="2"></Key>
    <Key
        android:codes="51"
        android:keyLabel="3"></Key>
</Row>
<Row>
    <Key
        android:codes="52"
        android:keyLabel="4"></Key>
    <Key
        android:codes="53"
        android:keyLabel="5"></Key>
    <Key
        android:codes="54"
        android:keyLabel="6"></Key>
</Row>
<Row>
    <Key
        android:codes="53"
        android:keyLabel="7"></Key>
    <Key
        android:codes="54"
        android:keyLabel="8"></Key>
    <Key
        android:codes="55"
        android:keyLabel="9"></Key>
</Row>
<Row>
    <Key
        android:codes="-10"
        android:keyLabel=""></Key>
    <Key
        android:codes="48"
        android:keyLabel="0"></Key>
    <Key
        android:codes="-5"
        android:keyIcon="@color/colorPrimary"></Key>
</Row>
</Keyboard>

2.繼承keyboardview
這里主要就是3個點:1、獲取按鍵布局(setkeyboard)2、繪制空白鍵跟刪除鍵(onDraw)3、設置回調(OnKeyPressListener)。
刪除按鈕我做了一點處理,因為直接使用獲取的dp(intrinsicWidth)的話圖片會比較大,不是很好看,為了協調一點我寬高各自除了個6,然后計算了上下左右的邊距(widthInterval,heightInterval),再進行的繪制。

這里用了自定義的屬性展示在這里:

  <declare-styleable name="NumKeyView">
    <attr name="gbColor" format="color|reference"></attr>
    <attr name="deleteDrawable" format="reference"></attr>
</declare-styleable>

NumKeyView的代碼

 public class NumKeyView extends KeyboardView implements OnKeyboardActionListener {
  //用于區分左下角空白按鍵,(要與xml里設置的數值相同)
  private int KEYCODE_EMPTY=-10;
   //刪除按鍵背景圖片
  private Drawable mDeleteDrawable;
  //最下面兩個灰色的按鍵(空白按鍵跟刪除按鍵)
  private int mBgColor;


 public NumKeyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context,attrs,0);
 }

 public NumKeyView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs, defStyleAttr);
 }

 private void init(Context context, AttributeSet attrs, int defStyleAttr) {
    TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.NumKeyView);
    mBgColor=ta.getColor(R.styleable.NumKeyView_gbColor, Color.RED);
    mDeleteDrawable=ta.getDrawable(R.styleable.NumKeyView_deleteDrawable);
    ta.recycle();
    //獲取xml中的按鍵布局
    Keyboard keyboard=new Keyboard(context,R.xml.numkeyview);
    setKeyboard(keyboard);
    setEnabled(true);
    setPreviewEnabled(false);
    setOnKeyboardActionListener(this);
    }

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    List<Keyboard.Key> keys=getKeyboard().getKeys();
    for (Keyboard.Key key:keys){
        //繪制空白鍵
        if (key.codes[0]==KEYCODE_EMPTY){
            drawKeyBackGround(key,canvas);
        }else if (key.codes[0]==Keyboard.KEYCODE_DELETE){
            //繪制刪除鍵背景
            drawKeyBackGround(key,canvas);
            //繪制按鍵圖片
            drawkeyDelete(key,canvas);
        }
    }
}
private void drawKeyBackGround(Keyboard.Key key, Canvas canvas) {
    ColorDrawable colordrawable=new ColorDrawable(mBgColor);
    colordrawable.setBounds(key.x,key.y,key.x+key.width,key.y+key.height);
    colordrawable.draw(canvas);
}
private void drawkeyDelete(Keyboard.Key key, Canvas canvas) {
    int intrinsicWidth=mDeleteDrawable.getIntrinsicWidth();
    int intrinsicHeight=mDeleteDrawable.getIntrinsicHeight();
    int drawWidth=key.width;
    int drawHeight=key.height;
    if(drawWidth<intrinsicWidth){
        drawHeight=drawWidth*intrinsicHeight/intrinsicWidth;
    }
    drawWidth=drawWidth/6;
    drawHeight=drawHeight/6;
    int widthInterval=(key.width-drawWidth)/2;
    int heightInterval=(key.height-drawHeight)/2;

    mDeleteDrawable.setBounds(key.x+widthInterval,key.y+heightInterval,key.x+widthInterval+drawWidth,key.y+heightInterval+drawHeight);
    mDeleteDrawable.draw(canvas);
}
//回調接口
public interface OnKeyPressListener{
    //添加數據回調
    void onInertKey(String text);
    //刪除數據回調
    void onDeleteKey();
}
private OnKeyPressListener mOnkeyPressListener;
public void setOnKeyPressListener(OnKeyPressListener li){
    mOnkeyPressListener=li;
}
@Override
public void onKey(int i, int[] ints) {
        if (i==Keyboard.KEYCODE_DELETE&&mOnkeyPressListener!=null){
            //添加數據回調
            mOnkeyPressListener.onDeleteKey();
        }else if (i!=KEYCODE_EMPTY){
            //刪除數據回調
            mOnkeyPressListener.onInertKey(Character.toString((char) i));
        }
}
@Override
public void onPress(int i) {

}

@Override
public void onRelease(int i) {

}



@Override
public void onText(CharSequence charSequence) {

}

@Override
public void swipeRight() {
    super.swipeRight();
}

@Override
public void swipeDown() {
    super.swipeDown();
}

@Override
public void swipeLeft() {
    super.swipeLeft();
}

@Override
public void swipeUp() {
    super.swipeUp();
}
}

注意!調用的時候,因為使用了自定義屬性(AS)所以注意添加下面一行代碼
xmlns:app="http://schemas.android.com/apk/res-auto"
3.其他部分
上面按鍵部分就做好了,下面看下自定義按鍵的中上面的接口回調

public class KeyDemo extends AppCompatActivity {
private EditText mEditText;
private NumKeyView mKeyView;
private Button mButton;
private LinearLayout mLinearlayout;
private PopupWindow mPop;
private LinearLayout mProgressBarLn;
private View mPopView;
private Handler mhandler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        mPop.dismiss();
        mKeyView.setVisibility(View.VISIBLE);
        mProgressBarLn.setVisibility(View.INVISIBLE);
        mButton.setText("完成");
    }
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_keyboard);
    init();
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //點擊按鈕顯示鍵盤
            mPop.showAtLocation(mLinearlayout, Gravity.BOTTOM,0,0);
        }
    });
    //設置回調,并進行文本的插入與刪除
    mKeyView.setOnKeyPressListener(new NumKeyView.OnKeyPressListener() {
        @Override
        public void onInertKey(String text) {
            if(mEditText.getText().length()<6){
                mEditText.append(text);
                //文本長度為6時隱藏鍵盤,顯示進度條,一段時間后pop消失
                if (mEditText.getText().length()==6){
                    mKeyView.setVisibility(View.INVISIBLE);
                    mProgressBarLn.setVisibility(View.VISIBLE);
                    mhandler.sendEmptyMessageDelayed(0x11,4000);
                }
            }
        }

        @Override
        public void onDeleteKey() {
            int last=mEditText.getText().length();
            if (last>0){
                //刪除最后一位
            mEditText.getText().delete(last-1,last);
            }
        }
    });

}

private void init() {
    mEditText= (EditText) findViewById(R.id.et);
    mButton= (Button) findViewById(R.id.bt);
    mLinearlayout= (LinearLayout) findViewById(R.id.ln);
    mPop=new PopupWindow();
    mPopView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.keyboard_pop,null);
    mPop.setContentView(mPopView);
    mPop.setTouchable(true);
    mPop.setFocusable(true);
    mPop.setBackgroundDrawable(new ColorDrawable());
    mPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
    mPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    mPop.setAnimationStyle(R.style.PopWindowstyle);
    mProgressBarLn= (LinearLayout) mPopView.findViewById(R.id.progressbar_ln);
    mKeyView= (NumKeyView) mPopView.findViewById(R.id.keyboardview);
}
}

主布局

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/ln"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
    android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/bt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="點擊彈出彈出窗"/>

</LinearLayout>

Pop布局

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.zhjh.keydemo.NumKeyView
    android:id="@+id/keyboardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:keyBackground="@color/colorAccent"
    app:gbColor="#eeeeee"
    app:deleteDrawable="@drawable/keyboard_backspace"
    />
<LinearLayout
    android:id="@+id/progressbar_ln"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="invisible"
    >
    <View
        android:layout_width="match_parent"
        android:layout_height="2px"
        android:background="#000000"
        ></View>
    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        style="@android:style/Widget.Holo.ProgressBar.Large"
        />
</LinearLayout>

</FrameLayout>

Pop動畫

彈出

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:fromXDelta="0"
    android:fromYDelta="100%"
    android:toXDelta="0"
    android:toYDelta="0"
    android:duration="1000"
    ></translate>

 </set>

消失

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
 android:toXDelta="0"
android:fromXDelta="0"
android:fromYDelta="0"
android:toYDelta="100%"
android:duration="1000"
></translate>
</set>

定義動畫

  <style name="PopWindowstyle">
   <item name="android:windowEnterAnimation">@anim/showanim</item>
   <item name="android:windowExitAnimation">@anim/dismissanim</item>
 </style>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,466評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,251評論 4 61
  • 今日開心播種,他日定有收成!無比感恩實修群老師和同學的帶領、督導和激勵!每晚都無比喜悅地為自己播種的好種子澆水施肥...
    如意寶閱讀 249評論 0 2
  • 昨夜星辰昨夜風 畫樓西畔桂堂東 時光流逝 歲月如梭 螺旋之光時光的旅程 波浪長發歲月的感知 女神在演奏唯美夜曲 巴...
    lynls8888閱讀 258評論 1 0
  • 班上頻繁的瑣碎和生活的日常,每天一樣,但也可以不一樣。 自從開始了100天寫作的練習,來自各方的反應,令生活不一樣...
    悅書_王小悅閱讀 216評論 3 5