Android afterTextChanged不会在每4个字符后输入一个空格

时间:2016-06-29 08:08:44

标签: java android

我试图设计一个简单的信用卡/借记卡表单。我有一个cardNumber EditText字段。当用户开始输入时,我希望我的应用程序在每4个数字后插入一个空格。我从this教程中获得了帮助并进行了一些修改,但它没有用。它不会在每4个数字后进入一个空格。

MainActivity.java

package *************************

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import java.security.Key;

public class MainActivity extends AppCompatActivity {

    private EditText cardNumber, expiryDate, CVV, nameOnCard;

    private boolean flag = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);//Locks the screen orientation
        init(); //Initializes the variables

        typefunc();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void init()
    {
        cardNumber = (EditText) findViewById(R.id.cardNumber); //Field for storing the card number
        expiryDate = (EditText) findViewById(R.id.expiryDate); //For storing the Expiry Date
        CVV = (EditText) findViewById(R.id.CVV); //For storing the CVV
        nameOnCard = (EditText) findViewById(R.id.nameOnCard); //For storing the name of the Cardholder
    }

    public void typefunc()
    {
        cardNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {

                if(s.length()==16)
                {
                    expiryDate.setVisibility(View.VISIBLE);
                    expiryDate.requestFocus();
                    CVV.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s)
            {

                char space = ' ';

                if (s.length() > 0 && (s.length() % 5) == 0)
                {
                    char c = s.charAt(s.length() - 1);

                    if (Character.isDigit(c))
                    {
                        s.insert(s.length() - 1, String.valueOf(space));
                    }
                }
            }
        });

        expiryDate.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if(s.length()==6)
                    CVV.requestFocus();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        CVV.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if(s.length()==3) {
                    nameOnCard.setVisibility(View.VISIBLE);


                }
            }

            @Override
            public void afterTextChanged(Editable s)
            {
                if(s.length()==3)
                    nameOnCard.requestFocus();
            }
        });
    }

}

4 个答案:

答案 0 :(得分:5)

这很好用

editText.addTextChangedListener(new TextWatcher() {
    private static final char space = ' ';

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        // Remove spacing char
        if (s.length() > 0 && (s.length() % 5) == 0) {
            final char c = s.charAt(s.length() - 1);
            if (space == c) {
                s.delete(s.length() - 1, s.length());
            }
        }
        // Insert char where needed.
        if (s.length() > 0 && (s.length() % 5) == 0) {
            char c = s.charAt(s.length() - 1);
            // Only if its a digit where there should be a space we insert a space
            if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 3) {
                s.insert(s.length() - 1, String.valueOf(space));
            }
        }
    }
});

并且不要忘记将以下属性添加到edittext

android:inputType="phone" android:maxLength="19"

希望这有助于:)

答案 1 :(得分:1)

试试这个:

Y

答案 2 :(得分:0)

那是因为afterTextChanged()

  

afterTextChanged() - 在>文字发生变化后,这将超出!   
调用此方法通知您,在s中的某个位置,文本已更改。

     

onTextChanged() - 这将超出,而文本正在发生变化   
调用此方法通知您,在s中,从start开始的计数字符刚刚替换了之前具有长度的旧文本。   
更多信息 here

所以你可以这样做:

cardNumber.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        if(cardNumber.length() == 4)
        {
            cardNumber.setText(cardNumber.getText() + " ");
        }
    }

    @Override
    public void afterTextChanged(Editable s)
    {

    }
});

注意: setText()也会触发onTextChanged(),但由于长度现在为5,因此无关紧要。

答案 3 :(得分:0)

从afterTextChanged方法中删除你的代码,并在onTextChanged方法中删除它,如下所示,

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count)
      {

            char space = ' ';

            if (s.length() > 0 && (s.length() % 5) == 0)
            {
                char c = s.charAt(s.length() - 1);

                if (Character.isDigit(c))
                {
                    //s.insert(s.length() - 1, String.valueOf(space));
                    cardNumber.append(String.valueOf(space));
                }
            }


            if(s.length()==16)
            {
                expiryDate.setVisibility(View.VISIBLE);
                expiryDate.requestFocus();
                CVV.setVisibility(View.VISIBLE);
            }
        }