本文主要是介绍安卓银行卡输入框实现自动加空格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安卓银行卡输入框实现自动加空格
最近涉及到一个需求,就是添加银行卡,需要在输入卡号的时候,自动每隔四位加一个空格,如下图
布局很简单:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="48dp"android:background="@android:color/white"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:gravity="center_vertical"android:paddingLeft="15dp"android:text="卡号:"android:textColor="#333333"android:textSize="14sp" /><EditTextandroid:id="@+id/et_cardNumber"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@null"android:gravity="center_vertical"android:inputType="number"android:maxLines="1"android:paddingLeft="15dp"android:textColor="#333333"android:textSize="14sp" /></LinearLayout></LinearLayout>
java代码
package com.demo.test.demo;import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;public class MainActivity extends Activity {private EditText et_cardNumber;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et_cardNumber = (EditText) findViewById(R.id.et_cardNumber);et_cardNumber.addTextChangedListener(watcher);}private TextWatcher watcher = new TextWatcher() {@Overridepublic void beforeTextChanged(CharSequence s, int start, int count, int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void afterTextChanged(Editable s) {String str = s.toString().trim().replace(" ", "");String result = "";if (str.length() >= 4) {et_cardNumber.removeTextChangedListener(watcher);for (int i = 0; i < str.length(); i++) {result += str.charAt(i);if ((i + 1) % 4 == 0) {result += " ";}}if (result.endsWith(" ")) {result = result.substring(0, result.length() - 1);}et_cardNumber.setText(result);et_cardNumber.addTextChangedListener(watcher);et_cardNumber.setSelection(et_cardNumber.getText().toString().length());//焦点到输入框最后位置}}};}
小弟第一次写博客,大神勿喷哈,希望能帮到需要的人
这篇关于安卓银行卡输入框实现自动加空格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!