-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathKeyboardView.java
1092 lines (983 loc) · 38.6 KB
/
KeyboardView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jsc.kit.keyboard;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
/*
Copyright 2019 JustinRoom
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* <br>Email:[email protected]
* <br>QQ:1006368252
* create time: 2019/3/27 15:01 Wednesday
*
* @author jsc
*/
public class KeyboardView extends LinearLayout {
private static final String TAG = "keyboard";
/**
* 仅支持水平方向上拖动
*/
public static final String ONLY_HORIZONTAL = "horizontal";
/**
* 仅支持垂直方向上拖动
*/
public static final String ONLY_VERTICAL = "vertical";
/**
* 支持任意方向上拖动
*/
public static final String ALL_DIRECTION = "all";
/**
* 不支持拖动
*/
public static final String NONE = "none";
@StringDef({ONLY_HORIZONTAL, ONLY_VERTICAL, ALL_DIRECTION, NONE})
@Retention(RetentionPolicy.SOURCE)
public @interface DragSupportModel {
}
//存储键盘上的按键view
private SparseArray<KeyView> viewSparseArray = new SparseArray<>();
//按键点击动画管理器。使用此管理器,避免同一个按键点击过快而造成按键的scale混乱。
private SparseArray<Animator> animatorSparseArray = new SparseArray<>();
//滑动松开手指自动滚动到合适的位置
private Animator autoReboundAnimator = null;
//使用该软键盘的输入框管理
private List<EditText> editTexts = new ArrayList<>(20);
//当前聚焦的输入框
private EditText focusedEditText = null;
//输入框touch后聚焦
private View.OnTouchListener touchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v instanceof EditText) {
if (!v.hasFocus())
v.requestFocus();
showKeyboardByEditTextInputType((EditText) v);
}
return false;
}
};
//按键点击监听
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
KeyView keyView = (KeyView) v;
dispatchKeyDownEvent(keyView);
}
};
//按键字体
private Typeface typeface = null;
//是否支持拖动
private @DragSupportModel
String curDragSupportModel = ONLY_VERTICAL;
//键盘拖动时touch坐标
private float touchX;
private float touchY;
//是否处于拖动模式
private boolean intoDragModel;
private int touchedPointerId = -1;
private Rect rect = new Rect();
//按键的基本宽度
private int keyWidth;
//按键的基本高度
private int keyHeight;
//按键的水平间隙
private int keyHorizontalSpace;
//按键的垂直间隙
private int keyVerticalSpace;
//存储键盘的尺寸。size[0]为键盘宽度,size[1]为键盘高度
private int[] size = new int[2];
//键盘类型。目前只支持三种:数字键盘、字母键盘、数字+字混合键盘
private @KeyUtils.KeyboardType
String keyboardType;
//是否为大写模式
private boolean upperCase = false;
//当键盘类型为数字+字混合键盘时,是否显示数字按键
private boolean showNumberKeys = false;
//创建按键时监听
private onCreateKeyListener createKeyListener = null;
//键盘的显隐监听
private OnKeyboardListener keyboardListener = null;
//自定义的按键监听
private OnKeyDownListener keyDownListener = null;
//********************* Constructors ***********************************//
public KeyboardView(Context context) {
this(context, null);
}
public KeyboardView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public KeyboardView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(VERTICAL);
int defaultKeyWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, context.getResources().getDisplayMetrics());
int defaultKeySpace = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics());
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.KeyboardView, defStyleAttr, 0);
int keyWidth = a.getDimensionPixelSize(R.styleable.KeyboardView_keyWidth, defaultKeyWidth);
int keyHeight = a.getDimensionPixelSize(R.styleable.KeyboardView_keyHeight, 0);
int horizontalSpace = a.getDimensionPixelSize(R.styleable.KeyboardView_keyHorizontalSpace, defaultKeySpace);
int verticalSpace = a.getDimensionPixelSize(R.styleable.KeyboardView_keyVerticalSpace, defaultKeySpace);
int boardType = a.getInt(R.styleable.KeyboardView_keyboardType, 0);
a.recycle();
if (keyHeight <= 0)
keyHeight = keyWidth * 3 / 5;
initKeySize(keyWidth, keyHeight);
initKeySpace(horizontalSpace, verticalSpace);
if (isInEditMode())
switch (boardType) {
case 0:
show(KeyUtils.TYPE_NINE_PALACE_NUMBER);
break;
case 1:
showNumberKeys = false;
show(KeyUtils.TYPE_LETTER);
break;
case 2:
showNumberKeys = true;
show(KeyUtils.TYPE_LETTER_NUMBER);
break;
case 3:
show(KeyUtils.TYPE_SYMBOL);
break;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (autoReboundAnimator != null) {
autoReboundAnimator.cancel();
}
switch (ev.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
//当没有进入键盘拖动模式
if (isCanDrag() && !intoDragModel) {
//这里使用PointerId防止多手指touch混乱问题
touchedPointerId = ev.getPointerId(0);
touchX = ev.getX();
touchY = ev.getY();
}
break;
case MotionEvent.ACTION_MOVE:
if (isCanDrag() && !intoDragModel && touchedPointerId == ev.getPointerId(0)) {
float tempX = ev.getX();
float tempY = ev.getY();
float dx = touchX - tempX;
float dy = touchY - tempY;
//当在任意方向上滑动大于等于8pixels时进入键盘拖动模式
if (Math.abs(dx) >= 8 || Math.abs(dy) >= 8) {
if (!isScaled()) {
intoDragModel = true;
//进入拖动模式后,所有按键不可用
enableAllKeys(false);
}
} else {
touchX = tempX;
touchY = tempY;
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (isCanDrag() && !intoDragModel) {
autoRebound();
}
break;
}
return intoDragModel;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//如果键盘是被缩小了,则不处理touch事件
if (isScaled() || !isCanDrag())
return super.onTouchEvent(event);
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
if (touchedPointerId == event.getPointerId(0)) {
touchX = event.getX();
touchY = event.getY();
}
break;
case MotionEvent.ACTION_MOVE:
if (touchedPointerId == event.getPointerId(0)) {
float tempX = event.getX();
float tempY = event.getY();
float dx = touchX - tempX;
float dy = touchY - tempY;
executeDrag(-dx, -dy);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (intoDragModel && touchedPointerId == event.getPointerId(0)) {
//抬起手指时,键盘智能复位
autoRebound();
//退出拖动模式
intoDragModel = false;
//恢复所有按键可用
enableAllKeys(true);
}
break;
}
return true;
}
/**
* 删除选中的字符串(清空输入框)
*/
public final void deleteAllInput() {
final EditText focusedView = getFocusedEditText();
if (focusedView == null)
return;
Editable editable = focusedView.getText();
int selectionStart = focusedView.getSelectionStart();
int selectionEnd = focusedView.getSelectionEnd();
if (selectionEnd > selectionStart) {
editable.delete(selectionStart, selectionEnd);
} else {
editable.delete(0, selectionStart);
focusedView.setSelection(0);
}
}
public final void deleteInput() {
final EditText focusedView = getFocusedEditText();
if (focusedView == null)
return;
Editable editable = focusedView.getText();
int selectionStart = focusedView.getSelectionStart();
int selectionEnd = focusedView.getSelectionEnd();
if (selectionEnd > selectionStart) {
editable.delete(selectionStart, selectionEnd);
} else {
int st = selectionStart - 1;
if (st < 0)
st = 0;
editable.delete(st, selectionStart);
focusedView.setSelection(st);
}
}
public final void insertInput(KeyBean bean) {
final EditText focusedView = getFocusedEditText();
if (focusedView == null)
return;
Editable editable = focusedView.getText();
int selectionStart = focusedView.getSelectionStart();
int selectionEnd = focusedView.getSelectionEnd();
CharSequence value = bean.getValue();
if (selectionEnd > selectionStart) {
editable.replace(selectionStart, selectionEnd, value);
} else {
editable.insert(selectionStart, value);
}
if (KeyUtils.isLinkedInputSymbolKey(bean.getKey())) {
int newSelectionStart = focusedView.getSelectionStart();
if (newSelectionStart - selectionStart == 2)
focusedView.setSelection(newSelectionStart - 1);
}
}
@Nullable
private EditText getFocusedEditText() {
if (focusedEditText == null || !focusedEditText.hasFocus())
for (EditText e : editTexts) {
if (e.hasFocus()) {
focusedEditText = e;
break;
}
}
return focusedEditText;
}
/**
* 初始化按键的宽高
*/
public void initKeySize(int keyWidth, int keyHeight) {
this.keyWidth = keyWidth;
this.keyHeight = keyHeight;
}
/**
* 初始化按键的水平和垂直间距
*/
public void initKeySpace(int horizontalSpace, int verticalSpace) {
this.keyHorizontalSpace = horizontalSpace;
this.keyVerticalSpace = verticalSpace;
}
public void initCustomTypeface(Typeface typeface) {
this.typeface = typeface;
}
/**
* 获取键盘的尺寸。
*
* @see #size
*/
public int[] getKeyboardSize() {
return size;
}
/**
* 创建按键
*/
private void createKeys() {
resetKeys();
List<List<KeyBean>> keys = KeyUtils.loadKeys(getKeyboardType(), getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
float maxWeight = getLayoutWeight(keys);
int row = keys.size();
int column = (int) maxWeight;
if (maxWeight > column) {
column++;
maxWeight = column;
}
size[0] = getPaddingLeft() + (keyWidth + 2 * keyHorizontalSpace) * column + getPaddingRight();
//宽度大于屏幕宽度,重新计算按键的宽度
if (size[0] > getResources().getDisplayMetrics().widthPixels) {
int availableWidth = getResources().getDisplayMetrics().widthPixels - getPaddingLeft() - getPaddingRight() - keyHorizontalSpace * 2 * column;
keyWidth = availableWidth / column;
size[0] = getPaddingLeft() + (keyWidth + 2 * keyHorizontalSpace) * column + getPaddingRight();
}
size[1] = getPaddingTop() + (keyHeight + 2 * keyVerticalSpace) * row + getPaddingBottom();
for (int i = 0; i < row; i++) {
List<KeyBean> tempKeys = keys.get(i);
LinearLayout layout = new LinearLayout(getContext());
layout.setOrientation(HORIZONTAL);
layout.setWeightSum(maxWeight);
addView(layout, new LayoutParams(size[0], LayoutParams.WRAP_CONTENT));
for (int j = 0; j < tempKeys.size(); j++) {
createKey(layout, tempKeys.get(j), keyHeight);
}
}
toggleUpperCase(upperCase);
updateNumKey();
}
private void createKey(LinearLayout layout, KeyBean bean, int keyHeight) {
int key = bean.getKey();
KeyView keyView = viewSparseArray.get(key);
boolean isCachedView = false;
if (keyView == null) {
isCachedView = true;
keyView = new KeyView(getContext());
keyView.setTypeface(typeface);
keyView.getTextKeyView().setTextColor(getKeyTextColor(key));
keyView.getTextKeyView().setTextSize(TypedValue.COMPLEX_UNIT_DIP, getKeyTextSize(key));
keyView.setOnClickListener(clickListener);
keyView.setOnLongClickListener(key == KeyUtils.KEY_DELETE ? new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
deleteAllInput();
return true;
}
} : null);
keyView.setEnabled(KeyUtils.isClickableKey(key));
keyView.setVisibility(key == KeyUtils.KEY_BLANK ? INVISIBLE : VISIBLE);
keyView.setBackgroundResource(getKeyBackground(key));
keyView.setBean(bean);
if (!KeyUtils.isNotKey(bean.getKey()))
viewSparseArray.put(key, keyView);
}
LayoutParams params;
ViewGroup.LayoutParams p = keyView.getLayoutParams();
if (p instanceof LayoutParams) {
params = (LayoutParams) p;
} else {
params = new LayoutParams(0, keyHeight);
}
params.weight = bean.getHorizontalWeight();
params.leftMargin = keyHorizontalSpace;
params.rightMargin = keyHorizontalSpace;
params.topMargin = keyVerticalSpace;
params.bottomMargin = keyVerticalSpace;
layout.addView(keyView, params);
if (createKeyListener != null)
createKeyListener.onKeyCreated(isCachedView, keyView, bean);
}
private float getLayoutWeight(List<List<KeyBean>> keys) {
float maxWeight = 0;
for (int i = 0; i < keys.size(); i++) {
List<KeyBean> childKeys = keys.get(i);
float rowWeightSum = 0;
for (int j = 0; j < childKeys.size(); j++) {
rowWeightSum = rowWeightSum + childKeys.get(j).getHorizontalWeight();
}
maxWeight = Math.max(maxWeight, rowWeightSum);
}
return maxWeight;
}
private int getKeyTextColor(@KeyUtils.KeyCode int key) {
return key == KeyUtils.KEY_NEXT ? Color.WHITE : 0xFF0A5028;
}
private float getKeyTextSize(int key) {
return createKeyListener == null ? 16 : createKeyListener.getKeyTextSize(getKeyboardType(), key);
}
private int getKeyBackground(int key) {
if (key == KeyUtils.KEY_NEXT)
return R.drawable.key_next_key_background_ripple;
if (KeyUtils.isFunctionKey(key))
return R.drawable.key_special_key_background_ripple;
return R.drawable.key_normal_key_background_ripple;
}
private void executeKeyboardReLocation(Animator.AnimatorListener listener) {
ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(
this,
PropertyValuesHolder.ofFloat(View.TRANSLATION_X, getTranslationX(), 0),
PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, getTranslationX(), 0)
).setDuration(300);
animator.addListener(listener);
animator.start();
}
private void dispatchKeyDownEvent(KeyView keyView) {
// playClickSound();
playClickAnimation(keyView);
boolean needExecuteDefaultKeyDownEvent = keyDownListener == null || !keyDownListener.onKeyDown(this, keyView);
if (!needExecuteDefaultKeyDownEvent)
return;
KeyBean bean = keyView.getBean();
switch (bean.getKey()) {
case KeyUtils.KEY_CLOSE://关闭
closeKeyboard();
break;
case KeyUtils.KEY_SCALE://键盘缩放
autoScale();
break;
case KeyUtils.KEY_ABC://切换为字母键盘
show(showNumberKeys ? KeyUtils.TYPE_LETTER_NUMBER : KeyUtils.TYPE_LETTER);
break;
case KeyUtils.KEY_DELETE://删除键
deleteInput();
break;
case KeyUtils.KEY_NEXT://聚焦下一个输入框
autoFocusNextEditText(bean);
break;
case KeyUtils.KEY_123://切换为带"ABC"按键的数字键盘
show(KeyUtils.TYPE_NINE_PALACE_NUMBER_WITH_ABC);
break;
case KeyUtils.KEY_AA://切换大小写
toggleUpperCase(!upperCase);
break;
case KeyUtils.KEY_NUM://字母键盘上显隐数字键
toggleNumberKeys();
updateNumKey();
break;
case KeyUtils.KEY_ENTER:
break;
case KeyUtils.KEY_SYMBOL:
show(KeyUtils.TYPE_SYMBOL);
break;
case KeyUtils.KEY_BACK:
show(showNumberKeys ? KeyUtils.TYPE_LETTER_NUMBER : KeyUtils.TYPE_LETTER);
break;
default:
insertInput(bean);
break;
}
}
private void enableAllKeys(boolean enable) {
for (int i = 0; i < viewSparseArray.size(); i++) {
viewSparseArray.get(viewSparseArray.keyAt(i)).setEnabled(enable);
}
}
private void executeDrag(float dx, float dy) {
ViewGroup parent = (ViewGroup) getParent();
int pLeft = parent.getPaddingLeft();
int pRight = parent.getWidth() - parent.getPaddingRight();
int pTop = parent.getPaddingTop();
int pBottom = parent.getHeight() - parent.getPaddingBottom();
int keyHeightWithSpace = keyHeight + keyVerticalSpace * 2;
getHitRect(rect);
if (dx + rect.left < pLeft) {
dx = pLeft - rect.left;
}
if (dx + rect.right > pRight) {
dx = pRight - rect.right;
}
if (dy + rect.top < pTop - (size[1] - keyHeightWithSpace - getPaddingBottom())) {
dy = pTop - (size[1] - keyHeightWithSpace - getPaddingBottom()) - rect.top;
}
if (dy + rect.bottom > pBottom + size[1] - keyHeightWithSpace - getPaddingTop()) {
dy = pBottom + size[1] - keyHeightWithSpace - getPaddingTop() - rect.bottom;
}
switch (curDragSupportModel) {
case ONLY_HORIZONTAL:
setTranslationX(getTranslationX() + dx);
break;
case ONLY_VERTICAL:
setTranslationY(getTranslationY() + dy);
break;
case ALL_DIRECTION:
setTranslationX(getTranslationX() + dx);
setTranslationY(getTranslationY() + dy);
break;
}
}
private void autoRebound() {
ViewGroup parent = (ViewGroup) getParent();
int pLeft = parent.getPaddingLeft();
int pRight = parent.getWidth() - parent.getPaddingRight();
int pTop = parent.getPaddingTop();
int pBottom = parent.getHeight() - parent.getPaddingBottom();
int keyHeightWithSpace = keyHeight + keyVerticalSpace * 2;
getHitRect(rect);
int offset = pBottom - rect.top;
if (offset > size[1] + keyHeightWithSpace * 2 + getPaddingBottom()) {
return;
} else if (offset >= size[1] - keyHeightWithSpace / 2 - getPaddingBottom()) {
offset = size[1];
} else if (offset >= keyHeightWithSpace + getPaddingTop()) {
offset = offset - getPaddingTop();
int rowCount = offset / keyHeightWithSpace;
int rest = offset % keyHeightWithSpace;
if (rest >= keyHeightWithSpace / 2)
rowCount++;
offset = rowCount * keyHeightWithSpace + getPaddingTop();
} else {
offset = keyHeightWithSpace + getPaddingTop();
}
int dy = pBottom - offset - rect.top;
if (Math.abs(dy) <= keyHeightWithSpace * 2 + getPaddingTop()) {
ObjectAnimator animator = ObjectAnimator.ofFloat(this, View.TRANSLATION_Y, getTranslationY(), getTranslationY() + dy).setDuration(Math.abs(dy));
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
autoReboundAnimator = animation;
// enableAllKeys(false);
}
@Override
public void onAnimationEnd(Animator animation) {
autoReboundAnimator = null;
// enableAllKeys(true);
}
@Override
public void onAnimationCancel(Animator animation) {
autoReboundAnimator = null;
// enableAllKeys(true);
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
}
}
private void autoScale() {
final float scaleValue = 0.8f;
if (isScaled()) {
Animator animator = ObjectAnimator.ofPropertyValuesHolder(this,
PropertyValuesHolder.ofFloat(View.SCALE_X, getScaleX(), 1.0f),
PropertyValuesHolder.ofFloat(View.SCALE_Y, getScaleY(), 1.0f),
PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, getTranslationY(), 0)
).setDuration(300);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
viewSparseArray.get(KeyUtils.KEY_SCALE).setEnabled(false);
}
@Override
public void onAnimationEnd(Animator animation) {
viewSparseArray.get(KeyUtils.KEY_SCALE).setEnabled(true);
}
@Override
public void onAnimationCancel(Animator animation) {
viewSparseArray.get(KeyUtils.KEY_SCALE).setEnabled(true);
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
animator.start();
} else {
ScaleAnimation animation = new ScaleAnimation(
1.0f, scaleValue,
1.0f, scaleValue,
ScaleAnimation.RELATIVE_TO_SELF, .5f,
ScaleAnimation.RELATIVE_TO_SELF, 1.0f
);
animation.setDuration(300);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
viewSparseArray.get(KeyUtils.KEY_SCALE).setEnabled(false);
}
@Override
public void onAnimationEnd(Animation animation) {
setScaleX(scaleValue);
setScaleY(scaleValue);
viewSparseArray.get(KeyUtils.KEY_SCALE).setEnabled(true);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
startAnimation(animation);
}
}
private boolean isScaled() {
return getScaleX() < 1.0f;
}
//******************************** 键盘显示(或隐藏) start **************************************************//
public void toggleVisibility() {
if (getVisibility() == VISIBLE)
closeKeyboard();
else
showKeyboard();
}
public void showKeyboard() {
if (getVisibility() != VISIBLE) {
show();
}
}
public void closeKeyboard() {
if (getVisibility() == VISIBLE) {
hide();
}
}
private void show() {
setVisibility(VISIBLE);
if (keyboardListener != null)
keyboardListener.onShow(this);
}
private void hide() {
setVisibility(GONE);
if (keyboardListener != null)
keyboardListener.onHide(this);
}
public void hideIfNecessary() {
if (getFocusedEditText() == null)
closeKeyboard();
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void onResume() {
final EditText focusedView = getFocusedEditText();
if (focusedView != null) {
showKeyboardByEditTextInputType(focusedView);
}
}
public void onPause() {
closeKeyboard();
}
public void onDestroy() {
removeAllEditText();
if (getParent() != null) {
((ViewGroup) getParent()).removeView(this);
}
}
//******************************** 键盘显示(或隐藏) end **************************************************//
private int getStatusBarHeight() {
int statusBarHeight = 0;
int resourceId = getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
statusBarHeight = getContext().getResources().getDimensionPixelSize(resourceId);
}
return statusBarHeight;
}
private void playClickSound() {
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null)
audioManager.playSoundEffect(SoundEffectConstants.CLICK);
}
private void playClickAnimation(KeyView keyView) {
int key = keyView.getBean().getKey();
//功能键不执行点击动画
if (KeyUtils.isFunctionKey(key)
|| KeyUtils.isNotKey(key)
|| key == KeyUtils.KEY_SPACE)
return;
Animator oldAnimator = animatorSparseArray.get(key);
if (oldAnimator != null) {
oldAnimator.cancel();
}
float scaleX = keyView.getScaleX();
float scaleY = keyView.getScaleY();
ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(
keyView,
PropertyValuesHolder.ofFloat(View.SCALE_X, scaleX, scaleX * 1.2f, scaleX),
PropertyValuesHolder.ofFloat(View.SCALE_Y, scaleY, scaleY * 1.2f, scaleY)
).setDuration(200);
animator.addListener(new KeyScaleAnimatorListener(key, scaleX, scaleY));
animatorSparseArray.put(key, animator);
animator.start();
}
private void toggleUpperCase(boolean upperCase) {
ensureInitialized();
this.upperCase = upperCase;
for (int i = KeyUtils.KEY_A; i <= KeyUtils.KEY_Z; i++) {
KeyView v = viewSparseArray.get(i);
if (v != null) {
v.updateUpperCase(upperCase);
}
}
KeyView upperCaseView = viewSparseArray.get(KeyUtils.KEY_AA);
if (upperCaseView != null)
upperCaseView.updateDrawable(upperCase ? R.drawable.key_icon_upper_case : R.drawable.key_icon_lower_case);
}
private void updateNumKey() {
KeyView toggleNumberView = viewSparseArray.get(KeyUtils.KEY_NUM);
if (toggleNumberView != null)
toggleNumberView.updateLabel(showNumberKeys ? KeyUtils.KEY_LABEL_HIDE_NUMBER : KeyUtils.KEY_LABEL_SHOW_NUMBER);
}
public final void autoFocusNextEditText(KeyBean bean) {
EditText editText = getFocusedEditText();
if (editText == null
|| KeyUtils.KEY_LABEL_DONE.equals(bean.getLabel().toString())) {
hide();
return;
}
editText.clearFocus();
focusedEditText = null;
int index = -1;
for (int i = 0; i < editTexts.size(); i++) {
if (editText == editTexts.get(i)) {
index = i;
break;
}
}
index++;
editTexts.get(index).requestFocus();
showKeyboardByEditTextInputType(editTexts.get(index));
}
public final void toggleNumberKeys() {
if (KeyUtils.TYPE_LETTER_NUMBER.equals(getKeyboardType())) {
showNumberKeys = false;
show(KeyUtils.TYPE_LETTER);
return;
}
if (KeyUtils.TYPE_LETTER.equals(getKeyboardType())) {
showNumberKeys = true;
show(KeyUtils.TYPE_LETTER_NUMBER);
}
}
public void setCreateKeyListener(onCreateKeyListener createKeyListener) {
this.createKeyListener = createKeyListener;
}
public void setKeyboardListener(OnKeyboardListener keyboardListener) {
this.keyboardListener = keyboardListener;
}
public void setKeyDownListener(OnKeyDownListener keyDownListener) {
this.keyDownListener = keyDownListener;
}
public void addAllInputView(View view) {
if (view == null || view instanceof KeyboardView) return;
if (view instanceof EditText) {
addInputView((EditText) view);
return;
}
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int i = 0; i < group.getChildCount(); i++) {
addAllInputView(group.getChildAt(i));
}
}
}
@SuppressLint("ClickableViewAccessibility")
public void addInputView(@NonNull EditText editText) {
if (editTexts.contains(editText))
return;
editTexts.add(editText);
editText.setShowSoftInputOnFocus(false);
editText.setOnTouchListener(touchListener);
}
public void removeAllInputView(View view) {
if (view == null || view instanceof KeyboardView) return;
if (view instanceof EditText) {
removeInputView((EditText) view);
return;
}
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int i = 0; i < group.getChildCount(); i++) {
removeAllInputView(group.getChildAt(i));
}
}
}
public void removeInputView(@NonNull EditText editText) {
editTexts.remove(editText);
if (focusedEditText != null && focusedEditText == editText) {
focusedEditText = null;
hide();
}
}
public void removeAllEditText() {
focusedEditText = null;
editTexts.clear();
}
private void showKeyboardByEditTextInputType(EditText editText) {
int inputType = editText.getInputType();
int imeOptions = editText.getImeOptions();
if (inputType == InputType.TYPE_NULL) {
hide();
return;
}
int action = InputType.TYPE_MASK_CLASS & inputType;
switch (action) {
case InputType.TYPE_CLASS_NUMBER:
case InputType.TYPE_CLASS_PHONE:
case InputType.TYPE_CLASS_DATETIME:
show(KeyUtils.TYPE_NINE_PALACE_NUMBER);
break;
default:
String keyboardType = getKeyboardType();
if (TextUtils.isEmpty(keyboardType)
|| KeyUtils.TYPE_NINE_PALACE_NUMBER.equals(keyboardType))
keyboardType = showNumberKeys ? KeyUtils.TYPE_LETTER_NUMBER : KeyUtils.TYPE_LETTER;
show(keyboardType);
break;
}
if (editTexts.isEmpty()) {
editTexts.size();
}
if (isLastEditText(editText)
|| (imeOptions & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_DONE) {
viewSparseArray.get(KeyUtils.KEY_NEXT).updateLabel(KeyUtils.KEY_LABEL_DONE);
} else {
viewSparseArray.get(KeyUtils.KEY_NEXT).updateLabel(KeyUtils.KEY_LABEL_NEXT);
}
}
private boolean isLastEditText(@NonNull EditText editText) {
if (!editTexts.isEmpty()) {
if (editText == editTexts.get(editTexts.size() - 1))
return true;
}
return false;
}
private void show(@KeyUtils.KeyboardType String keyboardType) {
final String lastKeyboardType = getKeyboardType();
if (!keyboardType.equals(lastKeyboardType)) {
setKeyboardType(keyboardType);
if ((KeyUtils.TYPE_NINE_PALACE_NUMBER.equals(lastKeyboardType)
|| KeyUtils.TYPE_NINE_PALACE_NUMBER.equals(keyboardType))
&& (getTranslationX() != 0 || getTranslationY() != 0))
executeKeyboardReLocation(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
createKeys();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
else
createKeys();
}
showKeyboard();
}
private void setKeyboardType(@KeyUtils.KeyboardType String keyboardType) {
this.keyboardType = keyboardType;
if (keyboardType.equals(KeyUtils.TYPE_LETTER_NUMBER)) {
showNumberKeys = true;
} else if (keyboardType.equals(KeyUtils.TYPE_LETTER)) {
showNumberKeys = false;
}
}
public String getKeyboardType() {