我是关于android的新手,想要当我在edittext中输入cnic然后在一些数字之后我可以把它放在它上面像:
12221-1338888-3
et_cnic = (EditText) findViewById(R.id.et_cnic);
我如何才能实现这一目标?请帮忙。
答案 0 :(得分:3)
试试这个
edt.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) {
String str = s.toString();
if(s.length() == 5 || s.length() == 13){
str += "-";
edt.setText(str);
edt.setSelection(str.length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
答案 1 :(得分:0)
String content="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edText = (EditText)findViewById(R.id.edText);
edText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if(s.length()%4 == 0){
int starting = content.length()==0?0:content.length();
content = content+s.subSequence(starting, start)+"-";
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
答案 2 :(得分:0)
et_cnic .addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(String.valueOf(et_cnic.getText()).length>X)//here x is the number of character after which "." will display on edit text
{
et_cnic.setText(String.valueOf(et_cnic.getText).substring(0,X)+"*")//x here same the number of charcter which you do not want to replace with"."
}
// TODO Auto-generated method stub
// Here you have to write your code for adding dashes.
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
答案 3 :(得分:0)
试试这个:
int x = 2;
edt = (EditText) findViewById(R.id.edt_test);
edt.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.toString().length() == x) {
edt.setText(s + "-");
edt.setSelection(s.toString().length() + 1);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
答案 4 :(得分:0)
int a = 0; // write this before on create
@Override
public void afterTextChanged(Editable s) {
if(s.length()==4 && a == 0){ // this logic will allow you to delete the "-" as well
number.setText(s+"-");
number.setSelection(s.length()+1);
a=1;
}
else if(s.length()<4 && a==1){
a=0;
}
}