最近項目有個新需求鲫售,需要自定義鍵盤硝拧。在強大的Android面前径筏,這點問題當然是可以滿足的,話不多說障陶,開始擼起來滋恬。
我們要實現(xiàn)如下圖的效果:
首先是自定義鍵盤的xml文件:customer_key_board.xml
<?xml version="1.0" encoding="UTF-8"?>
<Keyboard android:keyWidth="10%p" android:keyHeight="8%p"
android:horizontalGap="0.0px" android:verticalGap="0.0px"
xmlns:android="http://schemas.android.com/apk/res/android">
<Row android:verticalGap="1%p">
<Key android:codes="49" android:keyLabel="1"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="left" />
<Key android:codes="50" android:keyLabel="2"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="51" android:keyLabel="3"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="52" android:keyLabel="4"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="53" android:keyLabel="5"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="54" android:keyLabel="6"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="55" android:keyLabel="7"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="56" android:keyLabel="8"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="57" android:keyLabel="9"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="48" android:keyLabel="0"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="right"/>
</Row>
<Row android:verticalGap="1%p">
<Key android:codes="81" android:keyLabel="Q"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="left" />
<Key android:codes="87" android:keyLabel="W"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="69" android:keyLabel="E"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="82" android:keyLabel="R"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="84" android:keyLabel="T"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="89" android:keyLabel="Y"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="85" android:keyLabel="U"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="73" android:keyLabel="I"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="79" android:keyLabel="O"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="80" android:keyLabel="P"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="right" />
</Row>
<Row android:verticalGap="1%p">
<Key android:codes="65" android:keyLabel="A"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="left" />
<Key android:codes="83" android:keyLabel="S"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="68" android:keyLabel="D"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="70" android:keyLabel="F"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="71" android:keyLabel="G"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="72" android:keyLabel="H"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="74" android:keyLabel="J"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="75" android:keyLabel="K"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="76" android:keyLabel="L"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="right" />
<Key android:codes="-5" android:keyEdgeFlags="right"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:isRepeatable="true" />
<!--android:keyIcon="@drawable/keyboard_delete_bg"-->
</Row>
<Row >
<Key android:codes="90" android:keyLabel="Z"
android:horizontalGap="1%p" android:keyWidth="8.9%p"
android:keyEdgeFlags="left" />
<Key android:codes="88" android:keyLabel="X"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="67" android:keyLabel="C"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="86" android:keyLabel="V"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="66" android:keyLabel="B"
android:horizontalGap="1%p" android:keyWidth="8.9%p" />
<Key android:codes="78" android:keyLabel="N"
android:horizontalGap="1%p" android:keyWidth="8.9%p"/>
<Key android:codes="77" android:keyLabel="M"
android:horizontalGap="1%p" android:keyWidth="8.9%p"/>
<Key android:codes="-4"
android:keyEdgeFlags="right"
android:horizontalGap="1%p" android:keyWidth="28.9%p"
android:keyLabel="確定" android:isRepeatable="true" />
<!--android:keyIcon="@drawable/keyboard_confirm_bg"-->
</Row>
</Keyboard>
KeyBoard標簽下的keyWidth="10%p"表示下面的每個鍵寬度占parent寬度的10%(Key標簽下的keyWidth屬性會覆蓋parent中賦的值),horizontalGap是鍵與鍵之間的水平間隔抱究,verticalGap是垂直間隔恢氯。
Row標簽代表行,Key標簽代表鍵鼓寺。
拿第一行為例:Row標簽里有10個Key標簽酿雪,表示123...90 總共10個鍵,Key標簽里的horizontalGap屬性是鍵與鍵之間的水平間隔侄刽,keyWidth屬性是鍵的寬度大小指黎,在這里有一個計算關系,總共的鍵間隔寬度+總共的鍵寬度=你設置的鍵盤寬度州丹,我這個鍵盤是全屏的醋安,因此10個鍵寬度=10 * 8.9%p=89%屏幕寬度杂彭,有11個水平間隔寬度,每個水平間隔寬度1%吓揪,總水平間隔寬度=11 * 1%=11%亲怠,總寬度=89%+11%=100% 剛好一個屏幕寬度。具體的設計則靈活應變鍵的寬度和間隔寬度柠辞。
最左邊的鍵加入屬性android:keyEdgeFlags="left"团秽,最右邊的鍵加入屬性 android:keyEdgeFlags="right"。
codes屬性一般是該Key對應的ASCII碼叭首,當然也可以自定義习勤,只需要監(jiān)聽事件中返回給你這個codes值即可。keyLabel屬性就是該Key顯示在鍵盤上的string焙格,還有個keyIcon屬性是該Key顯示在鍵盤上的drawable图毕。
Key標簽下還有一個屬性isRepeatable表示是長按時是否重復輸入。
接下來就是自定義鍵盤的代碼了:
/**
* Created by hao on 2018/9/6.
* 車牌號專用鍵盤
*/
public class CarKeyboardView extends KeyboardView {
public CarKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
}
public CarKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Keyboard keyboard = getKeyboard();
if (keyboard == null) return;
List<Keyboard.Key> keys = keyboard.getKeys();
if (keys != null && keys.size() > 0) {
@SuppressLint("DrawAllocation")
Paint paint = new Paint();
paint.setTextAlign(Paint.Align.CENTER);
Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
paint.setTypeface(font);
paint.setAntiAlias(true);
for (Keyboard.Key key : keys) {
if (key.codes[0] == -4) {
Drawable dr = getContext().getResources().getDrawable(R.drawable.keyboard_confirm_bg);
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
if (key.label != null) {
paint.setTextSize(ScreenUtils.sp2px(getContext(),18));
//設置字體顏色
paint.setColor(getContext().getResources().getColor(R.color.color_white));
// 注意: 這個方法不支持硬件加速眷唉,所以我們要測試時必須先關閉硬件加速予颤。加上這一句
// setLayerType(LAYER_TYPE_SOFTWARE, null);
// paint.setShadowLayer(0.1f, 0, 0, getContext().getResources().getColor(R.color.color_white));
@SuppressLint("DrawAllocation")
Rect rect = new Rect(key.x, key.y, key.x + key.width, key.y + key.height);
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
int baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
// 下面這行是實現(xiàn)水平居中,drawText對應改為傳入targetRect.centerX()
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(key.label.toString(), rect.centerX(), baseline, paint);
// paint.setShadowLayer(0, 0, 0, 0);
}
} else if (key.codes[0] == -5) {
Drawable dr = getContext().getResources().getDrawable(R.drawable.keyboard_delete_bg);
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
} else if (key.codes[0] == 73||key.codes[0] == 79) { // notice 字母 I 和 O 設置特殊背景
Drawable dr = getContext().getResources().getDrawable(R.drawable.shape_keyboard_gray_color_r5);
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
if (key.label != null) {
paint.setTextSize(ScreenUtils.sp2px(getContext(),18));
paint.setColor(getContext().getResources().getColor(R.color.color_white_999999));
// 注意: 這個方法不支持硬件加速冬阳,所以我們要測試時必須先關閉硬件加速蛤虐。加上這一句
// setLayerType(LAYER_TYPE_SOFTWARE, null);
// paint.setShadowLayer(0.1f, 0, 0, getContext().getResources().getColor(R.color.color_white_999999));
@SuppressLint("DrawAllocation")
Rect rect = new Rect(key.x, key.y, key.x + key.width, key.y + key.height);
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
int baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(key.label.toString(), rect.centerX(), baseline, paint);
// paint.setShadowLayer(0, 0, 0, 0);
}
}
}
}
}
}
主要是繼承KeyboardView ,重寫onDraw方法肝陪,在onDraw方法里笆焰,根據不同的key.codes,設置不同的字體见坑、字體顏色嚷掠、按鍵背景等屬性,這里的代碼只是實現(xiàn)了我需要的需求荞驴,I不皆、O鍵背景置灰,刪除熊楼、確定鍵使用自定義的圖片霹娄,不同需求做相應處理即可。
接下來我們在處理一下點擊監(jiān)聽等事件:封裝進CarKeyBoardUtil里
/**
* Created by hao on 2018/9/6.
* 車牌號專用鍵盤
*/
public class CarKeyBoardUtil {
private View keyboardParentView;
private KeyboardView keyboardView;
private EditText editText;
private Keyboard keyboard;// 鍵盤
public CarKeyBoardUtil(View keyboardParentView, KeyboardView keyboardView, EditText editText) {
this.keyboardParentView = keyboardParentView;
this.keyboardView = keyboardView;
this.editText = editText;
this.keyboard = new Keyboard(editText.getContext(), R.xml.car_key_board);
this.editText.setInputType(InputType.TYPE_NULL);
this.keyboardView.setOnKeyboardActionListener(listener);
this.keyboardView.setKeyboard(keyboard);
this.keyboardView.setEnabled(true);
this.keyboardView.setPreviewEnabled(false);
}
private KeyboardView.OnKeyboardActionListener listener = new KeyboardView.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 = editText.getText();
int start = editText.getSelectionStart();
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
if (editable != null && editable.length() > 0) {
if (start > 0) {
editable.delete(start - 1, start);
}
}
break;
case Keyboard.KEYCODE_DONE:
if (runnable != null) {
keyboardView.postDelayed(runnable, 200);
} else {
if (keyboardParentView != null) {
keyboardParentView.setVisibility(View.GONE);
} else {
keyboardView.setVisibility(View.GONE);
}
}
break;
case 73:
case 79:
break;
default:
editable.insert(start, Character.toString((char) primaryCode));
break;
}
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
if (keyboardParentView != null) {
if (keyboardParentView.getVisibility() == View.VISIBLE) {
keyboardParentView.setVisibility(View.GONE);
}
} else {
if (keyboardView != null) {
if (keyboardView.getVisibility() == View.VISIBLE) {
keyboardView.setVisibility(View.GONE);
}
}
}
}
};
public void showKeyboard() {
if (keyboardParentView != null) {
int visibility = keyboardParentView.getVisibility();
if (visibility == View.GONE || visibility == View.INVISIBLE) {
keyboardParentView.setVisibility(View.VISIBLE);
}
} else {
if (keyboardView == null) {
return;
}
int visibility = keyboardView.getVisibility();
if (visibility == View.GONE || visibility == View.INVISIBLE) {
keyboardView.setVisibility(View.VISIBLE);
}
}
}
public void hideKeyboard() {
if (keyboardParentView != null) {
int visibility = keyboardParentView.getVisibility();
if (visibility == View.VISIBLE) {
keyboardParentView.setVisibility(View.GONE);
}
} else {
if (keyboardView == null) {
return;
}
int visibility = keyboardView.getVisibility();
if (visibility == View.VISIBLE) {
keyboardView.setVisibility(View.GONE);
}
}
}
public int getKeyboardVisibility() {
int visibility = View.GONE;
if (keyboardParentView != null) {
visibility = keyboardParentView.getVisibility();
} else {
if (keyboardView != null) {
visibility = keyboardView.getVisibility();
}
}
return visibility;
}
}
因為我這個鍵盤是用來輸入車牌號碼的鲫骗,因此需求是字母I和字母O不可點擊犬耻。我們只需要在OnKeyboardActionListener的onKey方法里,攔截codes為73(I)和79(O)执泰,不去處理即可枕磁。
最后是使用:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/act_key_board_et"
android:layout_width="match_parent"
android:layout_height="50dp"
android:inputType="text"
tools:ignore="Autofill,LabelFor" />
<LinearLayout
android:id="@+id/ky_keyboard_parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#d1d5dd"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingTop="10dp"
tools:ignore="RtlHardcoded">
<!--自定義,隨便改-->
<com.hccf.widget.keyboard.CarKeyboardView
android:id="@+id/ky_keyboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#d1d5dd"
android:focusable="true"
android:focusableInTouchMode="true"
android:keyBackground="@drawable/keyboard_click_bg"
android:keyTextColor="@color/edt_text_color"
android:keyTextSize="20sp"
android:shadowColor="#d1d5dd"
android:shadowRadius="0.1" />
</LinearLayout>
</RelativeLayout>
public class KeyBoardActivity extends AppCompatActivity {
private EditText act_key_board_et;
private CarKeyboardView keyboardView;
private View ky_keyboard_parent;
private CarKeyBoardUtil carKeyBoardUtil;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_key_board);
act_key_board_et = findViewById(R.id.act_key_board_et);
keyboardView = findViewById(R.id.ky_keyboard);
ky_keyboard_parent = findViewById(R.id.ky_keyboard_parent);
carKeyBoardUtil = new CarKeyBoardUtil(ky_keyboard_parent,keyboardView,act_key_board_et);
act_key_board_et.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (carKeyBoardUtil == null) {
carKeyBoardUtil = new CarKeyBoardUtil(ky_keyboard_parent,keyboardView,act_key_board_et);
}
carKeyBoardUtil.showKeyboard();
return false;
}
});
}
}
最終效果圖如下:
另外在補充一個术吝,也是很常見的自定義數(shù)字鍵盤:
具體實現(xiàn)就不在贅述计济,原理都差不多茸苇,代碼直接貼上了。
psd_key_board.xml
<?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.3333%p"
android:verticalGap="1dp">
<Row>
<Key
android:codes="49"
android:keyLabel="1" />
<Key
android:codes="50"
android:keyLabel="2" />
<Key
android:codes="51"
android:keyLabel="3" />
</Row>
<Row>
<Key
android:codes="52"
android:keyLabel="4" />
<Key
android:codes="53"
android:keyLabel="5" />
<Key
android:codes="54"
android:keyLabel="6" />
</Row>
<Row>
<Key
android:codes="55"
android:keyLabel="7" />
<Key
android:codes="56"
android:keyLabel="8" />
<Key
android:codes="57"
android:keyLabel="9" />
</Row>
<Row>
<Key
android:codes="-10"
android:keyLabel="" />
<Key
android:codes="48"
android:keyLabel="0" />
<Key
android:codes="-5"
android:keyLabel="" />
</Row>
</Keyboard>
PwdKeyboardView.java
/**
* Created by jhn on 2018/9/20.
* Description :
*/
public class PwdKeyboardView extends KeyboardView implements KeyboardView.OnKeyboardActionListener {
private static final String TAG = "PwdKeyboardView";
private static final int KEY_EMPTY = -10;
private int delKeyBackgroundColor = 0xffDADADA;
private Rect keyIconRect;
public PwdKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d(TAG, "PwdKeyboardView: two params");
init(context);
}
public PwdKeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
Log.d(TAG, "PwdKeyboardView: three params");
init(context);
}
private void init(Context context) {
Keyboard keyboard = new Keyboard(context, R.xml.psd_key_board); // 初始化 keyboard
setKeyboard(keyboard);
setEnabled(true);
setFocusable(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] == KEY_EMPTY) {
// 繪制空白鍵背景
drawKeyBackground(key, canvas, delKeyBackgroundColor);
}
if (key.codes[0] == Keyboard.KEYCODE_DELETE) {
// 刪除刪除按鍵背景
drawKeyBackground(key, canvas, delKeyBackgroundColor);
// 繪制刪除按鍵圖標
drawKeyIcon(key, canvas, getResources().getDrawable(R.drawable.icon_input_clear));
}
}
}
/**
* 繪制按鍵的背景
*/
private void drawKeyBackground(Keyboard.Key key, Canvas canvas, int color) {
ColorDrawable drawable = new ColorDrawable(color);
drawable.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
drawable.draw(canvas);
}
/**
* 繪制按鍵的 icon
*/
private void drawKeyIcon(Keyboard.Key key, Canvas canvas, Drawable iconDrawable) {
if (iconDrawable == null) {
return;
}
// 計算按鍵icon 的rect 范圍
if (keyIconRect == null || keyIconRect.isEmpty()) {
// 得到 keyicon 的顯示大小沦寂,因為圖片放在不同的drawable-dpi目錄下学密,顯示大小也不一樣
int intrinsicWidth = iconDrawable.getIntrinsicWidth();
int intrinsicHeight = iconDrawable.getIntrinsicHeight();
int drawWidth = intrinsicWidth;
int drawHeight = intrinsicHeight;
// 限制圖片的大小,防止圖片按鍵范圍
if (drawWidth > key.width) {
drawWidth = key.width;
// 此時高就按照比例縮放
drawHeight = (int) (drawWidth * 1.0f / intrinsicWidth * intrinsicHeight);
} else if (drawHeight > key.height) {
drawHeight = key.height;
drawWidth = (int) (drawHeight * 1.0f / intrinsicHeight * intrinsicWidth);
}
// 獲取圖片的 x,y 坐標,圖片在按鍵的正中間
int left = key.x + key.width / 2 - drawWidth / 2;
int top = key.y + key.height / 2 - drawHeight / 2;
keyIconRect = new Rect(left, top, left + drawWidth, top + drawHeight);
}
if (keyIconRect != null && !keyIconRect.isEmpty()) {
iconDrawable.setBounds(keyIconRect);
iconDrawable.draw(canvas);
}
}
@Override
public void onPress(int primaryCode) {
}
@Override
public void onRelease(int primaryCode) {
}
/**
* 處理按鍵的點擊事件
*/
@Override
public void onKey(int primaryCode, int[] keyCodes) {
Log.d(TAG, "onKey: primaryCode = " + primaryCode + ", keyCodes = " + Arrays.toString(keyCodes));
if (primaryCode == KEY_EMPTY) {
return;
}
if (listener != null) {
if (primaryCode == Keyboard.KEYCODE_DELETE) {
listener.onDelete();
} else {
listener.onInput(String.valueOf((char) primaryCode));
}
}
}
@Override
public void onText(CharSequence charSequence) {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeDown() {
}
@Override
public void swipeUp() {
}
public interface OnKeyListener {
// 輸入回調
void onInput(String text);
// 刪除回調
void onDelete();
}
private OnKeyListener listener;
public void setOnKeyListener(OnKeyListener listener) {
this.listener = listener;
}
}
attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="PwdEditText">
<attr name="style" format="enum">
<enum name="rectangle" value="0" />
<enum name="roundRectangle" value="1" />
</attr>
<attr name="pwdCount" format="integer" />
<attr name="strokeRadius" format="dimension" />
<attr name="strokeWidth" format="dimension" />
<attr name="strokeColor" format="color" />
<attr name="dotColor" format="color" />
<attr name="dotRadius" format="dimension" />
</declare-styleable>
</resources>
自定義的輸入框 PwdEditText.java
/**
* Created by jhn on 2018/9/20.
* Description :
*/
public class PwdEditText extends android.support.v7.widget.AppCompatEditText {
private final int STYLE_RECTANGLE = 0;
private final int STYLE_ROUND_RECTANGLE = 1;
private final int DEFAULT_STYLE = STYLE_RECTANGLE;
private final int DEFAULT_PWD_COUNT = 6;
private final float DEFAULT_STROKE_RADIUS = dp2Px(6);
private final float DEFAULT_STROKE_WIDTH = dp2Px(1);
private final int DEFAULT_STROKE_COLOR = Color.parseColor("#CCCCCC");
private final int DEFAULT_DOT_COLOR = Color.BLACK;
private final float DEFAULT_DOT_RADIUS = dp2Px(4);
private int style; // 控件的樣式传藏,矩形或圓角矩形
private float strokeRadius; // 邊框圓角的半徑
private float strokeWidth; // 邊框寬度
private int strokeColor; // 邊框顏色
private int pwdDotColor; // 密碼圓點顏色
private float pwdDotRadius; // 密碼圓點半徑
private int mWidth; // 控件寬度
private int mHeight; // 控件高度
private Paint strokePaint; // 繪制邊框paint
private Paint pwdDotPaint; // 繪制密碼圓點paint
private int mCount; // 密碼框個數(shù)
private float cellWidth; // 每個密碼框的寬度
private float paddingWidth;
private float halfStrokeWidth;
private int mCurInputCount; // 當前輸入字符個數(shù)
public PwdEditText(Context context) {
this(context, null);
}
/**
* 無論xml布局文件中有沒有寫自定義屬性腻暮,都調用兩個參數(shù)的構造函數(shù)
*/
public PwdEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initAttrs(context, attrs);
init();
}
/**
* 當有自定義的樣式時,調用三個參數(shù)的構造函數(shù)
*/
public PwdEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* 初始化自定義屬性
*/
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PwdEditText);
style = typedArray.getInt(R.styleable.PwdEditText_style, DEFAULT_STYLE);
mCount = typedArray.getInt(R.styleable.PwdEditText_pwdCount, DEFAULT_PWD_COUNT);
strokeColor = typedArray.getColor(R.styleable.PwdEditText_strokeColor, DEFAULT_STROKE_COLOR);
strokeWidth = typedArray.getDimension(R.styleable.PwdEditText_strokeWidth, DEFAULT_STROKE_WIDTH);
strokeRadius = typedArray.getDimension(R.styleable.PwdEditText_strokeRadius, DEFAULT_STROKE_RADIUS);
pwdDotColor = typedArray.getColor(R.styleable.PwdEditText_dotColor, DEFAULT_DOT_COLOR);
pwdDotRadius = typedArray.getDimension(R.styleable.PwdEditText_dotRadius, DEFAULT_DOT_RADIUS);
typedArray.recycle();
}
/**
* 初始化操作
*/
private void init() {
// 初始化邊框畫筆
strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
strokePaint.setColor(strokeColor);
strokePaint.setStrokeWidth(strokeWidth);
strokePaint.setStyle(Paint.Style.STROKE);
// 初始化圓點畫筆
pwdDotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
pwdDotPaint.setStyle(Paint.Style.FILL);
pwdDotPaint.setColor(pwdDotColor);
halfStrokeWidth = strokeWidth / 2;
// 設置光標不可見
setCursorVisible(false);
// 設置限定最大長度
setFilters(new InputFilter[]{new InputFilter.LengthFilter(mCount)});
// 設置無背景
// setBackgroundColor(getResources().getColor(android.R.color.transparent));
setBackgroundColor(Color.WHITE);
setMaxLines(1);
setFocusable(false);
this.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (onTextChangedListener != null) {
onTextChangedListener.beforeTextChanged(s, start, count, after);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (onTextChangedListener != null) {
onTextChangedListener.onTextChanged(s, start, before, count);
}
mCurInputCount = s.toString().length();
// 輸入完成的回調
if (mCurInputCount == mCount) {
if (onTextInputListener != null) {
onTextInputListener.onComplete(s.toString());
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (onTextChangedListener != null) {
onTextChangedListener.afterTextChanged(s);
}
}
});
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
// cellWidth = (mWidth - strokeWidth) / mCount;
paddingWidth = ScreenUtils.dp2px(getContext(), 15);
float allPaddingWidth = paddingWidth * (mCount - 1);
cellWidth = (mWidth - strokeWidth * mCount - allPaddingWidth) / mCount;
// Log.d(AppConfig.TAG, "paddingWidth---------->" + paddingWidth);
// Log.d(AppConfig.TAG, "allPaddingWidth---------->" + allPaddingWidth);
// Log.d(AppConfig.TAG, "cellWidth---------->" + cellWidth);
}
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
drawRect(canvas);
// drawHorizontalStroke(canvas);
// drawVerticalDivider(canvas);
drawPwdDot(canvas);
}
private void drawPwdDot(Canvas canvas) {
for (int i = 1; i <= mCurInputCount; i++) {
canvas.drawCircle(halfStrokeWidth + cellWidth / 2 + (cellWidth + paddingWidth + strokeWidth) * (i - 1), (mHeight) / 2,
pwdDotRadius, pwdDotPaint);
// canvas.drawCircle(halfStrokeWidth + cellWidth / 2 + (cellWidth + paddingWidth) * (i - 1), (mHeight) / 2,
// pwdDotRadius, pwdDotPaint);
}
}
// 繪制矩形方塊
private void drawRect(Canvas canvas) {
if (mCount == 1) {
RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, mWidth - halfStrokeWidth,
mHeight - halfStrokeWidth);
canvas.drawRoundRect(rectF, strokeRadius, strokeRadius, strokePaint);
} else {
for (int i = 0; i < mCount; i++) {
// 畫框框 左上毯侦,右下
float left;
if (i == 0) {
left = halfStrokeWidth;
} else {
left = halfStrokeWidth * (2 * i) + cellWidth * i + paddingWidth * i;
}
float top = strokeWidth / 2; // 就是halfStrokeWidth哭靖,語法不允許int x=0;y=x;
float right = halfStrokeWidth * (2 * i + 1) + cellWidth * (i + 1) + paddingWidth * i;
float bottom = mHeight - halfStrokeWidth;
RectF rectF = new RectF(
left,
top,
right,
bottom);
Log.d(getClass().getSimpleName(), "i------->" + i + "-----left------>" + left + "-----right----->" + right);
canvas.drawRoundRect(rectF, strokeRadius, strokeRadius, strokePaint);
}
}
}
// 繪制豎直方向分割線
private void drawVerticalDivider(Canvas canvas) {
if (mCount == 1) {
return;
}
for (int i = 1; i < mCount; i++) {
canvas.drawLine(halfStrokeWidth + cellWidth * i, halfStrokeWidth, halfStrokeWidth + cellWidth * i,
mHeight - halfStrokeWidth, strokePaint);
// // 第一條 line+cell*+padding*(i-1)
// canvas.drawLine(halfStrokeWidth + cellWidth * i + paddingWidth * (i - 1),
// halfStrokeWidth,
// halfStrokeWidth + cellWidth * i + paddingWidth * (i - 1),
// mHeight - halfStrokeWidth,
// strokePaint);
//
// // 第二條 line+cell*+line*i+padding*i
// canvas.drawLine(halfStrokeWidth + cellWidth * i + paddingWidth * i,
// halfStrokeWidth,
// halfStrokeWidth + cellWidth * i + paddingWidth * i,
// mHeight - halfStrokeWidth,
// strokePaint);
}
}
// 繪制水平方向分割線
private void drawHorizontalStroke(Canvas canvas) {
if (style == STYLE_RECTANGLE) {
canvas.drawRect(halfStrokeWidth, halfStrokeWidth, mWidth - halfStrokeWidth,
mHeight - halfStrokeWidth, strokePaint);
} else {
RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, mWidth - halfStrokeWidth,
mHeight - halfStrokeWidth);
canvas.drawRoundRect(rectF, strokeRadius, strokeRadius, strokePaint);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
return false;
}
return super.onKeyDown(keyCode, event);
}
private float dp2Px(int dpValue) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());
}
public interface OnTextChangedListener {
void beforeTextChanged(CharSequence s, int start, int count, int after);
void onTextChanged(CharSequence s, int start, int before, int count);
void afterTextChanged(Editable s);
}
public interface OnTextInputListener {
void onComplete(String result);
}
private OnTextInputListener onTextInputListener;
public void setOnTextInputListener(OnTextInputListener onTextInputListener) {
this.onTextInputListener = onTextInputListener;
}
private OnTextChangedListener onTextChangedListener;
public void addTextChangedListener(OnTextChangedListener listener) {
this.onTextChangedListener = listener;
}
}
fragment 彈出動畫dialog_enter.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_shortAnimTime"
android:fromYDelta="100%p"
android:toYDelta="0%p" />
</set>
fragment收回動畫dialog_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0%p"
android:toYDelta="100%p" />
</set>
fragment布局文件 fgm_dialog_pay_layout.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:orientation="horizontal"
tools:ignore="UseCompoundDrawables">
<ImageView
android:id="@+id/iv_exit"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:contentDescription="@string/app_name"
android:padding="5dp"
android:src="@drawable/icon_app_bar_close"
tools:ignore="RtlHardcoded" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="52dp"
android:gravity="center"
android:text="輸入交易密碼"
android:textColor="#494949"
android:textSize="18sp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.3dp"
android:background="#EBEBEB" />
<TextView
android:id="@+id/tv_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:textColor="#807877"
android:textSize="15sp"
tools:text="提現(xiàn)金額9.00元" />
<com.hao.pwdkeyboard.PwdEditText
android:id="@+id/et_input"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
app:pwdCount="6"
app:style="roundRectangle" />
<View
android:layout_width="match_parent"
android:layout_height="0.3dp"
android:layout_marginTop="35dp"
android:background="#CCCCCC" />
<com.hao.pwdkeyboard.PwdKeyboardView
android:id="@+id/key_board"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCCCCC"
android:keepScreenOn="true"
android:keyBackground="@drawable/selector_key_board"
android:keyTextColor="#494949"
android:keyTextSize="26sp"
android:shadowRadius="0" />
</LinearLayout>
最后就是PayDialogFragment.java
/**
* Created by jhn on 2018/9/20.
* Description :
*/
public class PayDialogFragment extends DialogFragment implements PwdEditText.OnTextInputListener {
private static final String TAG = "PayDialogFragment";
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container,
@Nullable Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: ");
//去掉dialog的標題,需要在setContentView()之前
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
getDialog().setCanceledOnTouchOutside(false);
View view = inflater.inflate(R.layout.fgm_dialog_pay_layout, null);
ImageView exitImgView = view.findViewById(R.id.iv_exit);
exitImgView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PayDialogFragment.this.dismiss();
}
});
final PwdEditText editText = view.findViewById(R.id.et_input);
editText.setOnTextInputListener(this);
PwdKeyboardView keyboardView = view.findViewById(R.id.key_board);
keyboardView.setOnKeyListener(new PwdKeyboardView.OnKeyListener() {
@Override
public void onInput(String text) {
Log.d(TAG, "onInput: text = " + text);
editText.append(text);
String content = editText.getText().toString();
Log.d(TAG, "onInput: content = " + content);
}
@Override
public void onDelete() {
Log.d(TAG, "onDelete: ");
String content = editText.getText().toString();
if (content.length() > 0) {
editText.setText(content.substring(0, content.length() - 1));
}
}
});
return view;
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
Window window = getDialog().getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.windowAnimations = R.style.DialogFragmentAnimation;
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//設置dialog的位置在底部
lp.gravity = Gravity.BOTTOM;
window.setAttributes(lp);
//去掉dialog默認的padding
// window.getDecorView().setPadding(0, 0, 0, 0);
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
@Override
public void onComplete(String result) {
Log.d(TAG, "onComplete: result = " + result);
Toast.makeText(getContext(), "input complete : " + result, Toast.LENGTH_SHORT).show();
}
}
使用的時候去操控這個PayDialogFragment就可以了叫惊。
例如:
PayDialogFragment payDialogFragment = new PayDialogFragment();
payDialogFragment.show(getSupportFragmentManager(), "payFragment");
講述了2種自定義鍵盤款青,如果改動不是很大做修,可以直接使用系統(tǒng)提供的KeyboardView霍狰,支持一部分屬性更改,但是如果改動較大則需要自己去重寫一個繼承自KeyboardView的CustomerKeyboardView饰及,具體實現(xiàn)根據不同的需求來做調整蔗坯,這方面Android提供了足夠的開放。